gpt4 book ai didi

java - 检查 BigDecimal 值是否在范围内

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:03:30 25 4
gpt4 key购买 nike

我有 BiGDecimal 价格,我需要检查它是否在某个范围内。例如应该是3个条件:

if (price >= 0 and price <=500) {
....
} else if (price >=500 && price <=1000) {
....
} else if (price > 1000) {
....
}

如何正确使用 BigDecimal 类型。

最佳答案

这可以使用 .compareTo() 实现方法。例如:

if ( price.compareTo( BigDecimal.valueOf( 500 ) > 0 
&& price.compareTo( BigDecimal.valueOf( 1000 ) < 0 ) {
// price is larger than 500 and less than 1000
...
}

从 JavaDoc 中引用(和释义):

The suggested idiom for performing these comparisons is: (x.compareTo(y) op 0), where op is one of the six comparison operators [(<, ==, >, >=, !=, <=)]

干杯,

关于java - 检查 BigDecimal 值是否在范围内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26996600/

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