public static void main(String args[]) {
double s=0;
int[] a = { 0, 0, 0, 0, 0, 0, 0, 0 };
double[] b = { 2.00, 1.00, 0.50, 0.20, 0.10, 0.05, 0.02, 0.01 };
double r=4;
double l = r /100;
s = 5.00 - l;
for (int i = 0; i < 8; i++) {
while (s != 0 && s > b[i]) {
s = s - b[i];
a[i]++;
}
System.out.println(s);
}
为什么显示的结果是
0.96
0.96
0.45999999999999996
0.05999999999999994
0.05999999999999994
0.00999999999999994
0.00999999999999994
0.00999999999999994
小数点后面精确到17位!
double q=n-0.2;
System.out.println(n);
System.out.println(m);
System.out.println(p);
System.out.println(q);
System.out.println(w);
System.out.println(x);
输入结果是:
0.45999999999999996
0.26
0.30000000000000004
0.25999999999999995
0.19999999999999996
0.09999999999999998神奇,也想知道为什么
它会自动的精确到17位!
如果我们要求要精确到几位小数,可以用DecimalFormat来做处理! import java.text.*;public static void main(String args[]) {
double s=0;
int[] a = { 0, 0, 0, 0, 0, 0, 0, 0 };
double[] b = { 2.00, 1.00, 0.50, 0.20, 0.10, 0.05, 0.02, 0.01 };
double r=4;
double l = r /100;
s = 5.00 - l;
DecimalFormat df = new DecimalFormat("0.00");//可以格式化这个double类型的数
for (int i = 0; i < 8; i++) {
while (s != 0 && s > b[i]) {
s = s - b[i];
a[i]++;
}
System.out.println(df.format(s));
}
可是为什么0.96不是17位啊
这是Double类toString()方法,
import sun.misc.FloatingDecimal;
public static String toString(double d) {
return new FloatingDecimal(d).toJavaFormatString();
}估计就是上面的底层实现的导致结果不同。