java - BigDecimal 值货币

标签 java bigdecimal

我有两个浮点值:

float value1 = 1.9f;
float value2 = 20;

我想将它们相乘并得到一个精确的结果,所以我使用 BigDecimal 并期望结果为 38:

BigDecimal total = new BigDecimal(value1).multiply(new BigDecimal(value2));

System.out.println(total); // 37.99999952316284179687500

当我对 10 和 1.9 进行相同的测试时,我得到 18.99999976158142089843750 而不是 19。

为什么我会失去精度?

最佳答案

这在 javadoc 中有解释对于 BigDecimal(double) 构造函数:

The results of this constructor can be somewhat unpredictable. One might assume that writing new BigDecimal(0.1) in Java creates a BigDecimal which is exactly equal to 0.1 (an unscaled value of 1, with a scale of 1), but it is actually equal to 0.1000000000000000055511151231257827021181583404541015625. This is because 0.1 cannot be represented exactly as a double (or, for that matter, as a binary fraction of any finite length). Thus, the value that is being passed in to the constructor is not exactly equal to 0.1, appearances notwithstanding.

虽然您的变量是 float ,但没有采用 float 的构造函数,因此它们被转换为 double 值。就像文档所说的那样,如果您使用字符串作为您的值,您将得到您期望的准确结果 (38)。

关于java - BigDecimal 值货币,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31193706/

相关文章:

java - 为什么 BigDecimal 构造函数实例具有不同的值?

java - 有谁知道这是否是 Java 库错误?

java - 如何将字符串统一解析成BigDecimal?

java - BigDecimal 和 MathContext 的不一致行为

java - Spring Security 和 Spring Social 外部身份验证

java - 代号一 javafx.util.pair

java - 使用 View 作为与 Hibernate 的连接表

java - 使用 MathContext 调用时,BigDecimal.divide() 会产生额外的精度数字

java - Eclipse Gradle集成无法正常工作

java - 如何在java中增加id并获取冗长的描述