2015-07-20 100 views
0

我正在創建一個英制到公制的轉換程序,爲每次轉換創建方法。我想將轉換前後的數字格式化爲兩位小數。截至目前,它顯示我「100英寸= 254釐米」。出了什麼問題?爲什麼十進制格式不能正確格式化?

String strConversionChoice, strValue; 
    double dblInputValue; 
    int intConversionChoice; 

    strConversionChoice = txtInputConversionChoice.getText(); 
    strValue = txtInputValue.getText(); 

    DecimalFormat x = new DecimalFormat("###.##"); 
    intConversionChoice = Integer.parseInt(strConversionChoice); 
    dblInputValue = Double.parseDouble(strValue); 

    if (intConversionChoice == 1) { 
     lblOutput.setText(x.format(dblInputValue) + " inches = " + x.format(inchesToCentimetres(dblInputValue))+ " centimetres"); 
    } 
    else if (intConversionChoice == 2) { 
     lblOutput.setText(x.format(dblInputValue) + " feet = " +x.format(feetToCentimetres(dblInputValue)) + " centimetres"); 
    } 
+0

也許本地化是cuplprit。你有沒有考慮到它? – Paolo

+1

如果你總是想要2個小數位,你需要使用'0'而不是'#'。 'DecimalFormat x =新的DecimalFormat(「###。00」)' – Codebender

+0

@Codebender謝謝! –

回答

0

當您在DecimalFormat的類使用#它顯示的數字,如果非零部分是別人在場它會顯示什麼,請使用0而不是#如果你想看到的數字,即使他們都爲0

看到這個link

+0

答案有時可能有小數位數,有沒有什麼辦法來解釋兩種可能性? –

+0

使用0可以根據需要打印數字。如果數字爲0,則只打印0;而如果使用#則零數字將不存在。因此@Codebender表示可以使用DecimalFormat x = new DecimalFormat(「 ### 00" )。打印正確的結果。 –

+0

啊好吧,那有效。謝謝! –