简体   繁体   中英

Rounding off double value in Java

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?

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
DecimalFormat f=new DecimalFormat("0.00");
String formate = f.format(value); 
double finalValue = (Double)f.parse(formate) ;
System.out.println(finalValue);

Use setRoundingMode as:

f.setRoundingMode( RoundingMode.DOWN );

How to round a number to n decimal places in Java

try this may be helpful:

 double d = 42.405;
 System.out.println(String.format("%2.2f", d));

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM