Java 比较 BigDecimal 是否大于零

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4164521/
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-08-14 12:12:49  来源:igfitidea点击:

Compare if BigDecimal is greater than zero

javacomparebigdecimal

提问by Santhosh

How can I compare if BigDecimalvalue is greater than zero?

如何比较BigDecimal值是否大于零?

采纳答案by Jon Skeet

It's as simple as:

这很简单:

if (value.compareTo(BigDecimal.ZERO) > 0)

The documentation for compareToactually specifies that it will return -1, 0 or 1, but the more general Comparable<T>.compareTomethod only guarantees less than zero, zero, or greater than zero for the appropriate three cases - so I typically just stick to that comparison.

文档compareTo实际上指定它将返回 -1、0 或 1,但更通用的Comparable<T>.compareTo方法仅保证在适当的三种情况下小于零、零或大于零 - 所以我通常只坚持这种比较。

回答by duffymo

Use compareTo()function that's built into the class.

使用compareTo()类中内置的函数。

回答by Anton Bessonov

Possible better way:

可能更好的方法

if (value.signum() > 0)

回答by Rama Krishna

 BigDecimal obj = new BigDecimal("100");
 if(obj.intValue()>0)
    System.out.println("yes");

回答by Satya M

using ".intValue()" on BigDecimal object is not right when you want to check if its grater than zero. The only option left is ".compareTo()" method.

当您想检查它是否大于零时,在 BigDecimal 对象上使用“.intValue()”是不正确的。剩下的唯一选项是“.compareTo()”方法。