在Java中舍入双重值 [英] Rounding off double value in Java
问题描述
目前我正在使用DecimalFormat类来舍入双倍值
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;
我正在使用Selenium进行浏览器应用测试,因此基于浏览器我需要完善值。
I'm doing browser app testing using Selenium, so based on the browser I need to round off the value.
例如:
IE四舍五入42.405到42.40而其他人则四舍五入到42.41。但如果值类似于42.403,42.406,那么我会看到所有浏览器的一致性。所以现在我必须在我的脚本中添加一个条件,所以如果浏览器是IE,那么舍入应该以这样的方式发生,我应该得到42.40,而对于其他浏览器应该得到42.41。我该怎么做?
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?
推荐答案
你可以指定 RoundingMode
/docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html#setRoundingMode%28java.math.RoundingMode%29rel =nofollow> DecimalFormatter
,但请根据您的需要选择它(我刚刚给出了一个使用 HALF_UP
的例子)。
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
或者,您也可以使用 BigDecimal
(知道为什么我们这样做)通常选择 BigDecimal
而不是 double
)。
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
这篇关于在Java中舍入双重值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!