gpt4 book ai didi

java - BigDecimal.ROUND_UP 的问题

转载 作者:行者123 更新时间:2023-12-01 08:13:14 29 4
gpt4 key购买 nike

为什么我的卖出价是 184.84?为什么它在 BigDecimal.ROUND_UP 中表现得像这样。我检查了 BigDecimal.ROUND_HALF_EVEN。效果很好。但我想知道为什么会这样。

for(int i = 0; i < 50; i++){
double sellrate = 184.83;
BigDecimal sellRate = new BigDecimal(sellrate);
sellRate = sellRate.setScale(2,BigDecimal.ROUND_UP);
System.out.println("sellRate : "+sellRate);
}

最佳答案

这就是原因:

double sellrate = 184.83;
BigDecimal sellRate = new BigDecimal(sellrate);
System.out.println("sellRate: " + sellRate);

打印

sellRate: 184.830000000000012505552149377763271331787109375

这在 BigDecimal JavaDoc 中有解释。 :

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.

使用String构造函数

BigDecimal sellRate = new BigDecimal("184.83");

如果您想获取 BigDecimal 的精确值。

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

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