[英]Rounding off double value in Java
Currently I'm using DecimalFormat class to round off double value 目前,我正在使用DecimalFormat类舍入双精度值
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. 我正在使用Selenium进行浏览器应用测试,因此基于浏览器,我需要四舍五入该值。
For Example: 例如:
IE rounds off 42.405 to 42.40 and others rounds off to 42.41. IE将42.405舍入为42.40,其他则舍入为42.41。 But if values are like 42.403, 42.406 then I see consistency across all browsers.
但是,如果值像42.403、42.406,那么我看到所有浏览器的一致性。 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.
因此,现在我必须在脚本中添加一个条件,以便如果浏览器是IE,那么四舍五入的方式应为42.40,而其他浏览器应为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
). 您可以为
DecimalFormatter
指定RoundingMode
,但是请根据需要进行选择(我刚刚使用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. 另外,您也可以使用
BigDecimal
(以防万一,为什么我们通常选择BigDecimal
而不是double
)。
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: 将setRoundingMode用作:
f.setRoundingMode( RoundingMode.DOWN );
How to round a number to n decimal places in Java 如何在Java中将数字四舍五入到小数点后n位
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 在的情况下,
42.405
您得到42.41
和的情况下42.404
- 42.4
。这样一
System.out.println(String.format("%2.2f", roundedValue));
you will get necessary output. 您将获得必要的输出。
42.41
or 42.40
correspondingly. 42.41
或42.40
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.