在Java中翻一番 [英] Round a double in Java
问题描述
静态双圆形(Double d,int precise){
BigDecimal bigDecimal = new BigDecimal(d);
bigDecimal = bigDecimal.setScale(精确,RoundingMode.HALF_UP);
return bigDecimal.doubleValue();
b
$ b但是,结果令人困惑:
System.out.println(round(2.655d,2)); // - > 2.65
System.out.println(round(1.655d,2)); // - > 1.66
为什么给这个输出?我使用jre 1.7.0_45。
解决方案您必须替换
BigDecimal bigDecimal = new BigDecimal(d);
与
BigDecimal bigDecimal = BigDecimal.valueOf(d);
您将得到预期的结果:
2.66
1.66
:
BigDecimal.valueOf(double val) - 使用Double.toString()方法提供的double的规范化字符串表示形式。这是将double(或float)转换为BigDecimal的首选方法。
$ b new BigDecimal(double val ) - 使用精确的十进制表示的二进制浮点值,因此这个构造函数的结果可能有点不可预知。
I have found this great solution for rounding:
static Double round(Double d, int precise) {
BigDecimal bigDecimal = new BigDecimal(d);
bigDecimal = bigDecimal.setScale(precise, RoundingMode.HALF_UP);
return bigDecimal.doubleValue();
}
However, the results are confusing:
System.out.println(round(2.655d,2)); // -> 2.65
System.out.println(round(1.655d,2)); // -> 1.66
Why is it giving this output? I'm using jre 1.7.0_45.
解决方案 You have to replace
BigDecimal bigDecimal = new BigDecimal(d);
with
BigDecimal bigDecimal = BigDecimal.valueOf(d);
and you will get the expected results:
2.66
1.66
Explanation from Java API:
BigDecimal.valueOf(double val) - uses the double's canonical string representation provided by the Double.toString() method. This is preferred way to convert a double (or float) into a BigDecimal.
new BigDecimal(double val) - uses the exact decimal representation of the double's binary floating-point value and thus results of this constructor can be somewhat unpredictable.
这篇关于在Java中翻一番的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!