public class doublePrecision {
public static void main(String[] args) {
double total = 0;
total += 5.6;
total += 5.8;
System.out.println(total);
}
}
上面的代码输出:
11.399999999999
如何使其只打印(或者能够使用它作为) 11.4?
public class doublePrecision {
public static void main(String[] args) {
double total = 0;
total += 5.6;
total += 5.8;
System.out.println(total);
}
}
上面的代码输出:
11.399999999999
如何使其只打印(或者能够使用它作为) 11.4?
/*
0.8 1.2
0.7 1.3
0.7000000000000002 2.3
0.7999999999999998 4.2
*/
double adjust = fToInt + 1.0 - orgV;
// The following two lines works for me.
String s = String.format("%.2f", adjust);
double val = Double.parseDouble(s);
System.out.println(val); // output: 0.8, 0.7, 0.7, 0.8
请使用java.math.BigDecimal
由于Double在内部是二进制小数,所以它们有时无法精确表示十进制小数。
浮点数是Java源代码中十进制数字的近似值。你看到的是双精度浮点数(double)和源代码(十进制编码)之间不匹配的结果。
Java会生成最接近的二进制近似值。你可以使用java.text.DecimalFormat来显示更好看的十进制值。
public class doublePrecision {
public static void main(String[] args) {
BigDecimal total = new BigDecimal("0");
total = total.add(new BigDecimal("5.6"));
total = total.add(new BigDecimal("5.8"));
System.out.println(total);
}
}
计算机以二进制方式存储数字,无法准确表示像33.333333333或100.0这样的数字。这是使用双精度浮点数时需要注意的一点。在向用户展示答案之前,您需要对其进行四舍五入处理。幸运的是,在大多数应用程序中,您不需要太多小数位。
// The number of 0s determines how many digits you want after the floating point
// (here one digit)
total = (double)Math.round(total * 10) / 10;
System.out.println(total); // prints 11.4
public static double sumDouble(double value1, double value2) {
double sum = 0.0;
String value1Str = Double.toString(value1);
int decimalIndex = value1Str.indexOf(".");
int value1Precision = 0;
if (decimalIndex != -1) {
value1Precision = (value1Str.length() - 1) - decimalIndex;
}
String value2Str = Double.toString(value2);
decimalIndex = value2Str.indexOf(".");
int value2Precision = 0;
if (decimalIndex != -1) {
value2Precision = (value2Str.length() - 1) - decimalIndex;
}
int maxPrecision = value1Precision > value2Precision ? value1Precision : value2Precision;
sum = value1 + value2;
String s = String.format("%." + maxPrecision + "f", sum);
sum = Double.parseDouble(s);
return sum;
}