Reputation: 487
Currently I'm using DecimalFormat class to round off double value
double d = 42.405;
DecimalFormat f = new DecimalFormat("##.00");
System.out.println(f.format(d));
output: 42.41;
I'm doing browser app testing using Selenium, so based on the browser I need to round off the value.
For Example:
IE rounds off 42.405 to 42.40 and others rounds off to 42.41. But if values are like 42.403, 42.406 then I see consistency across all browsers. So now I have to put a condition in my script so if browser is IE then round off should happen in such a way that I should get 42.40 and for other browsers is should get 42.41. How can i do this?
Upvotes: 0
Views: 2028
Reputation: 45060
You can specify the RoundingMode
for the DecimalFormatter
, but please choose it as per your needs(I've just given an example using HALF_UP
).
double d = 42.405;
DecimalFormat f = new DecimalFormat("##.00");
f.setRoundingMode(RoundingMode.HALF_UP);
System.out.println(f.format(d)); // Prints 42.41
Alternatively, you can also use BigDecimal
(incase you know why we usually go for BigDecimal
instead of double
) for the same.
double d = 42.405;
BigDecimal bd = new BigDecimal(d);
bd = bd.setScale(2, RoundingMode.HALF_UP);
System.out.println(bd.doubleValue()); // Prints 42.41
Upvotes: 3
Reputation: 2830
Also you can do it "handly" as follow
double d = 42.405;
final double roundedValue = (Math.round(d * 100) / (double) 100);
In case of 42.405
you get 42.41
and in case of 42.404
- 42.4
And so after
System.out.println(String.format("%2.2f", roundedValue));
you will get necessary output. 42.41
or 42.40
correspondingly.
Upvotes: 0
Reputation: 339
Use setRoundingMode as:
f.setRoundingMode( RoundingMode.DOWN );
How to round a number to n decimal places in Java
Upvotes: 1
Reputation: 2691
try this may be helpful:
double d = 42.405;
System.out.println(String.format("%2.2f", d));
Upvotes: 0
Reputation: 378
DecimalFormat f=new DecimalFormat("0.00");
String formate = f.format(value);
double finalValue = (Double)f.parse(formate) ;
System.out.println(finalValue);
Upvotes: 1