|
-
December 2nd, 2004, 12:36 PM
#1
Senior Member
Precision iN Java
Hello Guys!!!
I have a question for a precision in java.
i am using
double num=.349995953;
now the thing is that i want to round of variable "num" to two decimal places. so that the value of num become .35
I am not falimiar with how to set this precision, I wonder if any one can help me.
Regards
Harbir
U get What U pay for. 
-
December 2nd, 2004, 02:27 PM
#2
Hi
A quick (ugly) way of doing this would be the following:
pseudo:
1. double num2=num*100 (since you want to round to 2 decimal places)
2. int rounded=round(num2)
3. num=rounded/100.
The code[1]:
Code:
// JDK1.0.2
public class divers {
public static void main(String args[]){
divers d = new divers();
d.testRound();
}
public void testRound(){
double r = round(3.1537, 2);
System.out.println(r); // output is 3.15
}
double round(double value, int decimalPlace) {
double power_of_ten = 1;
while (decimalPlace-- > 0)
power_of_ten *= 10.0;
return Math.round(value * power_of_ten)
/ power_of_ten;
}
}
//JDK1.1
import java.math.*;
public class divers {
public static void main(String args[]){
divers d = new divers();
d.testRound();
}
public void testRound(){
double r = 3.1537;
int decimalPlace = 2;
BigDecimal bd = new BigDecimal(r);
bd = bd.setScale(decimalPlace,BigDecimal.ROUND_HALF_UP);
r = bd.doubleValue();
System.out.println(r); // output is 3.15
}
}
Cheers
[1] http://www.rgagnon.com/javadetails/java-0016.html
If the only tool you have is a hammer, you tend to see every problem as a nail.
(Abraham Maslow, Psychologist, 1908-70)
-
December 2nd, 2004, 09:15 PM
#3
http://java.sun.com/j2se/1.5.0/docs/...berFormat.html
You need SDK 1.5.0 for this I think, maybe it works on 1.4.2 as well.
/  \\

-
December 3rd, 2004, 03:36 PM
#4
NumberFormat works on 1.4.2 as well - I've used it quite successfully before. The only thing about it is that it can be a bit annoying to set up...but I guess it's debatable whether Math.round(...) is any easier.
ac
-
December 10th, 2004, 11:32 AM
#5
Senior Member
U get What U pay for. 
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
|