java Java中的BigDecimal问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7525284/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 20:20:03  来源:igfitidea点击:

BigDecimal Problem in java

javabigdecimal

提问by Sunil kumar

BigDecimal bd= new BigDecimal("00.0000000000");
//now bd format to 0E-10
if(BigDecimal.ZERO.equals(bd) || bd.equals("0E-10"))
{
 flag=true; 
}

There are two problems in the above code

上面的代码有两个问题

  1. why variable bdautomatically format to 0E-10
  2. ifcondition results false value, ie it does not enter inside ifblock.
  1. 为什么变量bd 会自动格式化为0E-10
  2. if条件结果为假值,即它不会进入if块内。

Can anyone suggest. thanks

任何人都可以建议。谢谢

回答by NPE

You've given the constructor ten digits after the decimal point, so even though all of them are zero, BigDecimalhas decided to set its internal scaleto 10. This explains the -10in "0E-10".

您已经为构造函数指定了小数点后的十位数字,因此即使它们都为零,BigDecimal也决定将其内部设置scale为 10。这解释了-10in "0E-10"

As to equals, the Javadoc says:

至于equalsJavadoc 说

Compares this BigDecimalwith the specified Objectfor equality. Unlike compareTo, this method considers two BigDecimalobjects equal only if they are equal in value and scale (thus 2.0 is not equal to 2.00 when compared by this method).

将此BigDecimal与指定Object的相等进行比较。与 不同compareTo,此方法仅在两个BigDecimal对象的值和比例相等 时才认为它们相等(因此,通过此方法进行比较时,2.0 不等于 2.00)。

Bottom line:

底线:

  1. Use compareTo()instead of equals().
  2. Don't directly compare BigDecimalto Stringas this won't work.
  1. 使用compareTo()代替equals()
  2. 不要直接比较BigDecimalString因为这行不通。

回答by Howard

You can test for zero using

您可以使用

bd.signum() == 0

BigDecimal.equalsalso includes scale (which is 10 in your case) and thus fails. In general you should use compareToin order to compare BigDecimals.

BigDecimal.equals还包括比例(在您的情况下为 10),因此失败。一般来说,您应该使用compareTo以进行比较BigDecimals

回答by Matthew Farwell

The BigDecimal uses a scale of 10 because you've given it ten digits after the decimal point, which answers your first point.

BigDecimal 使用 10 的比例,因为您在小数点后给它十位数字,这回答了您的第一点。

For the if, for the first part, you are comparing 0 with 00.00000000000 (the scale is different, so they aren't the same). In the second, you're comparing a String with a BigDecimal. Which won't work.

对于 if,对于第一部分,您将 0 与 00.00000000000 进行比较(比例不同,因此它们不相同)。在第二个中,您将 String 与 BigDecimal 进行比较。这行不通。