在Java中将字符串转换为带有2个小数位的十进制数

Java中,我试图将一串格式“###.##”解析为浮点数.该字符串应始终具有2个小数位.

即使String的值为123.00,浮点数也应为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
最佳答案
这行是你的问题:

litersOfPetrol = Float.parseFloat(df.format(litersOfPetrol));

在那里你根据需要将你的浮动格式化为字符串,但是然后该字符串再次转换为浮点数,然后你在stdout中打印的是你的浮点数得到了标准格式.看看这段代码

import java.text.DecimalFormat;

String stringLitersOfPetrol = "123.00";
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);
stringLitersOfPetrol = df.format(litersOfPetrol);
System.out.println("liters of petrol before putting in editor : "+stringLitersOfPetrol);

顺便说一句,当你想使用小数时,忘记存在double和float,就像其他人建议的那样,只使用BigDecimal对象,它会为你省去很多麻烦.

转载注明原文:在Java中将字符串转换为带有2个小数位的十进制数 - 代码日志