请自由评论我.以下程序出了什么问题.它给出了不同的圆形结果.
public class Test {
public static String round(double value, int places) {
BigDecimal bd = new BigDecimal(value);
bd = bd.setScale(places, RoundingMode.HALF_UP);
return bd.toPlainString();
}
public static void main(String[] args) throws Exception {
double value1 = 1.1234565;
System.out.println(round(value1, 6));
double value2 = 1.1235;
System.out.println(round(value2, 3));
}
}
为什么这样出来?
1.123457
1.123 --> Actually, I expect 1.124
在Doc(eclipse)
解决方法:
Translates a double into a BigDecimal which is the exact decimal representation of the double’s binary floating-point value. The scale of the returned BigDecimal is the smallest value such that (10scale × val) is an integer.
这些笔记也很有启发性,我建议你阅读它们.
您传入的值恰好是1.12349999999999994315658113919198513031005859375,因为它是最接近1.1235的两倍.如果在调用setScale之前打印出bd.toPlainString(),则可以看到.因此,这不是1.123和1.124之间的中间 – 它最接近1.123.
如果你想要BigDecimal值恰好是1.1235,我建议你把它作为String传递:
import java.math.*;
public class Test {
public static String round(String value, int places) {
BigDecimal bd = new BigDecimal(value);
bd = bd.setScale(places, RoundingMode.HALF_UP);
return bd.toPlainString();
}
public static void main(String[] args) throws Exception {
String value1 = "1.1234565";
System.out.println(round(value1, 6));
String value2 = "1.1235";
System.out.println(round(value2, 3));
}
}
或者你可以使用BigDecimal.valueOf(double)而不是new BigDecimal(double) – 但是你仍然遇到的问题是你已经将真正的原始源数据(源代码中的文本)转换为二进制浮点数,可能会丢失信息.
标签:java
来源: https://codeday.me/bug/20190717/1488669.html