2016-12-05 21 views
-1

我有這樣的代碼:的NumberFormat不給正確的數字

import java.text.NumberFormat; 
import java.text.ParseException; 
import java.util.Locale; 
import java.util.Scanner; 


class EntryPoint { 
    static Locale czech = null; 

    static Locale getCzechLocale(){ 
     if (czech == null){ 
      czech = new Locale("cs","CZ"); 
     } 
     return czech; 
    } 

    public static void main(String[] args) { 
     Scanner sn = new Scanner(System.in); 
     NumberFormat nf = NumberFormat.getInstance(getCzechLocale()); 
     System.out.println(nf.format(12000.5)); 
     NumberFormat nf2 = NumberFormat.getCurrencyInstance(getCzechLocale()); 
     try { 
      String input = sn.nextLine(); 
      System.out.println(input); 
      Number n = nf.parse(input); 
      System.out.println(n.floatValue()); 
     }catch(ParseException javaTextParseException){ 
      System.err.println("Unable to parse input String"); 
     } 
    } 

} 

我要存檔這件事:如果我輸入數字「12 000,5」(這是節目顯示)程序解析和此String和意志顯示號碼「12000.5」。 我有什麼不對? 現在,如果我輸入「12 000,5」無「的標誌節目顯示浮點數‘12.0’而不是‘12000.5’

解決 NumberFormat.Parse(字符串)將結束於第一空間字符,所以如果我修剪()和替換(」」,‘’),那麼結果是正常

+0

爲什麼你認爲這是錯的? – Henry

+0

我在系統上使用「en_US」語言環境,所以我需要以「cs_CZ」格式輸入文本並在「en_US」中顯示 –

+0

@亨利,因爲如果我輸入「12 000,5」,我得到結果「12.0」 –

回答

1

NumberFormat不會停在第一個空格上。只是您使用的NumberFormat使用的分組分隔符是一個不間斷的空格,而不是一個常規空格。

如果您複製並粘貼程序的輸出以將其作爲輸入傳遞,它將會高興地將其解析回12000.5,因爲輸出使用了不間斷空格。

如果你想讓它使用普通空格字符,請使用

DecimalFormat nf = (DecimalFormat) NumberFormat.getInstance(new Locale("cs", "CZ")); 
DecimalFormatSymbols decimalFormatSymbols = nf.getDecimalFormatSymbols(); 
decimalFormatSymbols.setGroupingSeparator(' '); 
nf.setDecimalFormatSymbols(decimalFormatSymbols); 
-2

試試這個代碼,它爲我工作。

 Locale czech = new Locale("cs", "CZ"); 
     Scanner sn = new Scanner(System.in); 
     NumberFormat nf = NumberFormat.getInstance(czech); 
     String input = sn.nextLine(); 
     System.out.println(nf.format(Double.parseDouble(input))); 
     sn.close(); 
+0

不工作對我來說:/Library/Java/JavaVirtualMachines/jdk1.8.0_111.jdk/Contents/Home/bin/java -Dfile.encoding = UTF-8 -jar/Users/jvalek/IdeaProjects/HelloWorld/out/artifacts/HelloWorld_jar/HelloWorld的.jar 12 000,5 在線程 「主」 java.lang.NumberFormatException例外:對於輸入字符串: 「12 000,5」 \t在sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043) \t在sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110) \t at java.lang.Double.parseDouble(Double.java:538) \t在EntryPoint.main(EntryPoint.java:22) 過程完成退出代碼1 –

+0

您無需自己輸入12 000,5,只需輸入12000.5,上面的代碼就可以完成剩下的工作。 –

-2

如果您使用的是像## ###,#固定格式使用固定考慮格式解析器,如DecimalFormat:

NumberFormat nf = new DecimalFormat("### ###.##"); 
Number n=nf.parse("123 456,78");