簡體   English   中英

使用DecimalFormat的問題

[英]Problems using DecimalFormat

當我要在回歸后打印出系數時,我在使用DecimalFormat時遇到了問題。

這是代碼中遇到問題的部分;

DecimalFormat twoDForm = new DecimalFormat("0.00");   
private double s(double d){  
    return Double.valueOf(twoDForm.format(d));  
}  

這是eclipse中的錯誤信息;

Exception in thread "main" java.lang.NumberFormatException: For input string: "0,16"  
 at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)  
 at java.lang.Double.valueOf(Unknown Source)  
 at model.ARF2.s(ARF2.java:126)  
 at model.ARF2.printBestModel(ARF2.java:114)  
 at testing.testclass3.bestForecastingModel(testclass3.java:69)  
 at testing.testclass3.main(testclass3.java:36)  

如果有人對如何修復代碼有任何激增,請告訴我。 我想要系數上的兩位小數。

謝謝

拉爾斯

采用:

    DecimalFormat twoDForm = new DecimalFormat("#.##");
    DecimalFormatSymbols dfs = new DecimalFormatSymbols();
    dfs.setDecimalSeparator('.');
    twoDForm.setDecimalFormatSymbols(dfs);

http://download.oracle.com/javase/1.4.2/docs/api/java/text/DecimalFormat.html

以下摘錄似乎是您問題的一部分:

要獲取特定區域設置的NumberFormat(包括默認區域設置),請調用NumberFormat的工廠方法之一,例如getInstance()。 通常,不要直接調用DecimalFormat構造函數,因為NumberFormat工廠方法可能返回除DecimalFormat之外的子類。 如果需要自定義格式對象,請執行以下操作:

 NumberFormat f = NumberFormat.getInstance(loc);
 if (f instanceof DecimalFormat) {
     ((DecimalFormat) f).setDecimalSeparatorAlwaysShown(true);
 }

您可能想要使用applyPattern方法:

applyPattern

public void applyPattern(String pattern)將給定的模式應用於此Format對象。 模式是各種格式屬性的簡寫規范。 這些屬性也可以通過各種setter方法單獨更改。 此例程設置的整數位數沒有限制,因為這是典型的最終用戶需求; 如果要設置實際值,請使用setMaximumInteger。 對於負數,請使用以分號分隔的第二個模式

示例“#,#00.0#” - > 1,234.56

這意味着至少2個整數位,1個小數位,最多2個小數位。

示例:“#,#00.0#;(#,#00.0#)”表示括號中的底片。

在負模式中,忽略最小和最大計數; 這些被認為是以積極模式設定的。

拋出:NullPointerException - 如果pattern為null IllegalArgumentException - 如果給定的模式無效。

您遇到了i18n問題。 DecimalFormat使用您的默認語言環境,將小數分隔符指定為 但是, Double.valueOf不使用區域設置。 它總是期望小數分隔符是

如果你想分析與格式化字符串DecimalFormat ,那么你需要使用DecimalFormat.parse

我想你打算做的是:

private static String s(double d) {
   return twoDForm.format(d);
}

檢查您的區域設置。

DecimalFormat twoDForm = new DecimalFormat("0.00");   
    private double s(double d){ 

    String doubleString =  displayNumberAmount(twoDForm.format(d));
        return Double.valueOf(doubleString);  
    } 

    public static String displayNumberAmount(String amount) {

            NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.CANADA_FRENCH);

            Number number = 0;

            try {
                number = numberFormat.parse(amount);

            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return String.format(Locale.US, "%1$,.2f", number);
        }

你想格式化數字嗎? 還是圍繞它? 如果你正在格式化它,不應該是你的“s”方法(壞名稱IMO,順便說一句,但它是私有的,所以這是你的調用)返回java.lang.String而不是double

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM