在Java中将字符串转换为带有2个小数位的十进制数
发布时间:2020-12-15 02:06:21 所属栏目:Java 来源:网络整理
导读:在 Java中,我试图将一串格式“###.##”解析为浮点数.该字符串应始终具有2个小数位. 即使String的值为123.00,浮点数也应为123.00,而不是123.0. 这是我到目前为止: System.out.println("string liters of petrol putting in preferences is " + stringLitersO
在
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对象,它会为你省去很多麻烦. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |