Java浮点值格式
我试着用这个:
String t="4.99999999";
t = String.format("%.2f",Float.valueOf(t));
我想让它打印4.99
,但它写了5.00
。你知道为什么吗
你可以在下面搜索框中键入要查询的问题!
我试着用这个:
String t="4.99999999";
t = String.format("%.2f",Float.valueOf(t));
我想让它打印4.99
,但它写了5.00
。你知道为什么吗
# 1 楼答案
试一试
# 2 楼答案
这里有两个问题。一个是float不能区分
4.99999999
和5.0
,即Float.valueOf()
将其解析为5.0
。doubledo具有足够的精度。另一个问题是5.0是%2f
的正确行为。您要求的是两个小数点,4.9999999显然四舍五入为5.00。既然String.format()
行为不是您想要的,那么您想要什么,即为什么4.99是您用例的正确行为编辑:如果您试图截断两个小数点,请查看此处:How can I truncate a double to only two decimal places in Java
# 3 楼答案
一般来说,在考虑十进制数时,不能使用浮点数(或双精度浮点数)
简单的例子:
将打印:
Java将在内部存储浮点数和双精度浮点数作为“二进制值”。把小数点转换成二进制分数会引起很多令人惊讶的事情
如果要处理十进制数,必须使用
BigDecimal
或类似的类如何使用此功能的示例:
# 4 楼答案
如果希望它显示
4.99
,为什么不提取子字符串如果希望它总是有两位小数,那么可以使用
BigDecimal
。使用BigDecimal
可以将比例设置为小数点后2位,并向下舍入,以便像4
这样的数字打印出来4.00