2012-03-07 28 views
0

爲什麼結果不同? 如果我使用浮動它得到,675,如果我使用雙我得到,674 ...是不是很奇怪?Java DecimalFormat顯示float和double的不同結果

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 

感謝

+0

因爲'float'和'double'不一樣。 ;) – 2012-03-07 11:17:58

回答

7

如果我使用浮得到它,675,如果我使用雙我得到,674 ...心不是很奇怪嗎?

並不特別。你正在格式化不同的值。特別是,假設你真正改變你的代碼,以便它會編譯(與f後綴爲浮動),即使你指定 9位,float只會可靠代表7.

的都不數字是,正好是 12345.6745。事實上,精確值:

f = 12345.6748046875 
d = 12345.674499999999170540831983089447021484375 

看看那些爲什麼小數點後第三位是5 f和4 d很明顯。

如果你想保留十進制數字,你應該考慮使用BigDecimal

2

你有一個表示錯誤的問題。當你有溢出時,這更明顯。

long l = 123456789L; 
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= 123456789in hex 112210f47de98115 
d= 1.23456789E18 
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,short,charbyte準確地代表最低位。