java 字符串转数字保留两位小数,将字符串转换为Java中2位小数的十进制数

"本文探讨了如何在Java中正确解析字符串"###.##"格式,确保始终保留两位小数。通过实例展示了使用DecimalFormat避免精度丢失的方法,并建议使用BigDecimal处理浮点数问题。"
摘要由CSDN通过智能技术生成

In Java, I am trying to parse a string of format "###.##" to a float. The string should always have 2 decimal places.

Even if the String has value 123.00, the float should also be 123.00, not 123.0.

This is what I have so far:

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);

It prints:

string liters of petrol putting in preferences is 010.00

liters of petrol before putting in editor: 10.0

解决方案

This line is your problem:

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

There you formatted your float to string as you wanted, but but then that string got transformed again to a float, and then what you printed in stdout was your float that got a standard formatting. Take a look at this code

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);

And by the way, when you want to use decimals, forget the existence of double and float as others suggested and just use BigDecimal object, it will save you a lot of headache.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值