 1. ## 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  Reply With Quote

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:

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-- &gt; 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  Reply With Quote

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.  Reply With Quote

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  Reply With Quote

5. Thanx Guys  Reply With Quote

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•