gpt4 book ai didi

java - BigDecimal 值货币

转载 作者:行者123 更新时间:2023-11-29 05:03:32 24 4
gpt4 key购买 nike

我有两个浮点值:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com