我的数据类型有一个奇怪的问题: 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上尝试过,但没有任何改变。
应该如何发生?有什么想法吗?
此致
答案 0 :(得分:1)
这并不容易。我会使用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));
答案 1 :(得分:0)
根据javadoc
If at least one of the operands to a numerical operator is of type double, then the operation is carried out using 64-bit floating-point arithmetic, and the result of the numerical operator is a value of type double. If the other operand is not a double, it is first widened (§5.1.5) to type double by numeric promotion (§5.6).