0

为什么结果不同?如果我使用 float 它会得到 ,675,如果我使用 double 我会得到 ,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

谢谢

4

2 回答 2

7

如果我使用 float 它会得到 ,675,如果我使用 double 我会得到 ,674 ......这不是很奇怪吗?

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

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

f = 12345.6748046875
d = 12345.674499999999170540831983089447021484375

看看那些,很明显为什么小数点后第三位是 5f和 4 d

如果你想保留十进制数字,你应该考虑使用BigDecimal.

于 2012-03-07T11:14:12.163 回答
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准确地表示最高位,而、int和准确地表示最低位。shortcharbyte

于 2012-03-07T11:23:47.937 回答