用特定数字浮点精度 [英] Float precision with specific numbers

查看:135
本文介绍了用特定数字浮点精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的值给我错误的精度。只用特定的数字来观察。这可能是一个浮动表示的问题,但想知道具体原因。

  String m =154572.49; //\"154,572.49\" ; 
Float f = Float.parseFloat(m);
System.out.println(f);

打印输出是 154572.48 154572.49

解决方案

与您在Java中输入内容完全相同,请使用 BigDecimal 而不是float。



浮点数对于小数本质上是不准确的,因为许多以十进制结尾的数字(如0.1)是二进制和浮点数的重复数字以二进制形式存储。


The following value gives me wrong precision. It is observed with only specific numbers. It might be a floating representation problem, but wanted to know the specific reason.

String m = "154572.49"; //"154,572.49";
Float f = Float.parseFloat(m);
System.out.println(f);

The output it is printing is 154572.48 instead of 154572.49.

解决方案

If you want decimal numbers to come out as exactly as you entered them in Java, use BigDecimal instead of float.

Floating point numbers are inherently inaccurate for decimals because many numbers that terminate in decimal (e.g. 0.1) are recurring numbers in binary and floating point numbers are stored as a binary representation.

这篇关于用特定数字浮点精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆