Java DecimalFormat显示float和double的不同结果

时间:2012-03-07 11:12:09

标签: java floating-point double decimalformat

为什么结果不同? 如果我使用浮动它得到,675如果我使用双我得到,674 ...不是很奇怪吗?

float f = 12345.6745;
double d = 12345.6745;

Locale l = Locale.forLanguageTag("es-ES");
DecimalFormat df = (DecimalFormat) NumberFormat.getInstance(l);
print(df.format(f));
>> 12.345,675

l = Locale.forLanguageTag("es-ES");
DecimalFormat df = (DecimalFormat) NumberFormat.getInstance(l);
print(df.format(d));
>> 12.345,674

由于

2 个答案:

答案 0 :(得分:7)

  

如果我使用浮动它得到,675如果我使用双我得到,674 ...不是很奇怪吗?

不是特别的。您正在格式化不同的值。特别是,假设您实际更改了代码,使其编译(浮点数带有f后缀),即使您指定 9位数,float只能可靠地代表7。

这两个数字都不是正好 12345.6745。实际上,确切的值是:

f = 12345.6748046875
d = 12345.674499999999170540831983089447021484375

看看这些,很明显为什么f的第三个小数位为5,d为4。

如果您想保留小数位,您应该考虑使用BigDecimal

答案 1 :(得分:2)

您遇到代表错误的问题。当你有溢出时,这一点就更明显了。

long l = 1234567890123456789L;
double d = l;
float f = l;
int i = (int) l;
short s = (short) l;
char ch = (char) l;
byte b = (byte) l;
System.out.println("l= " + l + " in hex " + Long.toHexString(l));
System.out.println("d= " + d);
System.out.println("f= " + f);
System.out.println("i= " + i + " in hex " + Integer.toHexString(i));
System.out.println("s= " + s + " in hex " + Integer.toHexString(s & 0xFFFF));
System.out.println("(int) ch= " + (int) ch +  " in hex " + Integer.toHexString(ch));
System.out.println("b= " + b +  " in hex " + Integer.toHexString(b));

打印

l= 1234567890123456789 in hex 112210f47de98115
d= 1.23456789012345677E18
f= 1.23456794E18
i= 2112454933 in hex 7de98115
s= -32491 in hex 8115
(int) ch= 33045 in hex 8115
b= 21 in hex 15

只有long可以无错误地表示此值(加上BigInteger和BigDecimal)所有其他数据类型都有不同的错误。 floatdouble准确表示最高位,而intshortcharbyte准确表示最低位。