2013-08-20 100 views
1

我格式化的十進制數,我有以下標準進行格式化:格式化十進制數

  • 數量應該是最多兩位小數(10.1234 => 10.12
  • 如果有小數點後只有一個數字那麼它將最終用一個額外的0(10.5 => 10.50
  • 千分離器將是逗號(12345.2345 => 12,345.23

我已經寫了下面的邏輯:

double x = Double.parseDouble(value.toString()); 
String dec = x % 1 == 0 ? new java.text.DecimalFormat("###,###.##").format(x) : new java.text.DecimalFormat("###,###.00").format(x); 

現在是打印:

11111111111110.567=>11,111,111,111,110.57 
111111111111110.567=>111,111,111,111,110.56 
1111111111111110.567=>1,111,111,111,111,110.60 
11111111111111110.567=>11,111,111,111,111,110 
111111111111111110.567=>111,111,111,111,111,104 
1111111111111111110.567=>1,111,111,111,111,111,170 

我不明白爲什麼行爲的變化。我應該怎樣打印1111111111111111110.567作爲1,111,111,111,111,111,110.57

回答

3

問題是,首先,您不能完全代表1111111111111111110.567作爲double。 (你甚至不能代表你的最短值正是,但是當你增加幅度不準確會顯著增加。)

一個double只反正有一些有用的數據,約17顯著位 - 你正在試圖獲得22位數字。

如果您想要更高的精度,請使用BigDecimal - 但請注意,這也會改變其他事物。無論如何,你想表達什麼樣的價值?自然值(權重,距離等)適用於double;人爲值(特別是貨幣值)適用於BigDecimal

3

我設法得到這個(你必須使用BigDecimal):

import java.math.BigDecimal; 
import java.text.NumberFormat; 

public class Sandbox { 
    public static void main(String[] args) { 
     BigDecimal x = new BigDecimal("1111111111111111110.567"); 
     DecimalFormat formatter = new DecimalFormat("###,###.00"); 
     System.out.println(formatter.format(x)); 
    } 
} 

OUTPUT:

1,111,111,111,111,111,110.57 

資源鏈接:DecimalFormatBigDecimal

還有一件事,你要輸入BigDecimal號碼作爲String否則會導致問題。

BigDecimal x = new BigDecimal(1111111111111111110.567) will output the following. 

1,111,111,111,111,111,168.00