作者:陈卓0561_979 | 来源:互联网 | 2023-10-13 12:32
参见英文答案 > Why do I see a double variable initialized to some value like 21.4 as 21.399999618530273?                                    14个
我有一个奇怪的数据类型问题:double.
这是我的代码:
public class Example {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
double a = 1.0;
for(int i =0; i<10;i++){
System.out.println("Number => " + a );
a += 0.1;
}
}
}
输出应该是:
Number => 1.0
Number => 1.1
Number => 1.2
Number => 1.3
Number => 1.4
Number => 1.5
Number => 1.6
Number => 1.7
Number => 1.8
Number => 1.9
但是,此代码示例的结果是:
Number => 1.0
Number => 1.1
Number => 1.2000000000000002
Number => 1.3000000000000003
Number => 1.4000000000000004
Number => 1.5000000000000004
Number => 1.6000000000000005
Number => 1.7000000000000006
Number => 1.8000000000000007
Number => 1.9000000000000008
我使用eclipse来编译这个代码块.我尝试了netbeans,但没有任何改变.
怎么会发生?有任何想法吗?
问候
解决方法:
这并不容易.我会用Commons-Math
for (int i = 0; i <10; i++) {
a = Precision.round(a, 1); // <- round to 1 digit after decimal point
...
我认为唯一的Java SE替代方案是
a = Double.parseDouble(String.format(Locale.US, "%.1f", a));