gpt4 book ai didi

java - BigDecimal 行为的差异

转载 作者:行者123 更新时间:2023-12-02 14:19:34 26 4
gpt4 key购买 nike

我有两段代码new BigDecimal("1.240472701")new BigDecimal(1.240472701)。现在,如果我在这两种方法上使用java的compareTo方法,那么我发现它们不相等。

当我使用java的System.out.println()方法打印值时。我对这两个值得到不同的结果。例如

new BigDecimal("1.240472701") -> 1.240472701

new BigDecimal(1.240472701) -> 1.2404727010000000664291519569815136492252349853515625

所以我想了解这可能是什么原因?

最佳答案

可以引用public BigDecimal(double val)的Java文档为此:

public BigDecimal(double val) 

Translates a double into a BigDecimal which is the exact decimal representation of the double's binary floating-point value. The scale of the returned BigDecimal is the smallest value such that (10^scale × val) is an integer.

  • 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.

  • The String constructor, on the other hand, is perfectly predictable: writing new BigDecimal("0.1") creates a BigDecimal which is exactly equal to 0.1, as one would expect. Therefore, it is generally recommended that the String constructor be used in preference to this one.

  • When a double must be used as a source for a BigDecimal, note that this constructor provides an exact conversion; it does not give the same result as converting the double to a String using the Double.toString(double) method and then using the BigDecimal(String) constructor. To get that result, use the static valueOf(double) method.

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

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