在Java中,我試圖將一個格式爲"###.##"
的字符串解析爲float。該字符串應始終有2個小數位。將字符串轉換爲Java中帶有2位小數的十進制數
即使字符串的值爲123.00
,float也應該是123.00
而不是123.0
。
這是我到目前爲止有:
System.out.println("string liters of petrol putting in preferences is " + stringLitersOfPetrol);
Float litersOfPetrol = Float.parseFloat(stringLitersOfPetrol);
DecimalFormat df = new DecimalFormat("0.00");
df.setMaximumFractionDigits(2);
litersOfPetrol = Float.parseFloat(df.format(litersOfPetrol));
System.out.println("liters of petrol before putting in editor: " + litersOfPetrol);
它打印:
string liters of petrol putting in preferences is 010.00
liters of petrol before putting in editor: 10.0
不要解析格式化字符串又可能? – x4rf41
'setMinimumFractionDigits'聽起來更合適。 – Maroun
不解析爲浮點數 –