问题描述
我有一个将unitPrice设置为BigDecimal数据类型的域类.现在,我正在尝试创建一种比较价格的方法,但是似乎我没有BigDecimal数据类型的比较运算符.我需要更改数据类型还是其他方法?
I have a domain class with unitPrice set as BigDecimal data type. Now I am trying to create a method to compare price but it seems like I can't have comparison operators in BigDecimal data type. Do I have to change data type or is there other way around?
推荐答案
类BigDecimal
的每个对象都有一个方法 compareTo
可以用来将其与另一个BigDecimal进行比较.然后根据需要将compareTo
的结果与> 0
,== 0
或< 0
进行比较.阅读文档,您将找到答案.
Every object of the Class BigDecimal
has a method compareTo
you can use to compare it to another BigDecimal. The result of compareTo
is then compared > 0
, == 0
or < 0
depending on what you need. Read the documentation and you will find out.
运算符==
,<
,>
等只能用于原始数据类型,例如int
,long
,double
或它们的包装器类,例如Integer
和.
The operators ==
, <
, >
and so on can only be used on primitive data types like int
, long
, double
or their wrapper classes like Integer
and Double
.
来自compareTo
的文档:
两个BigDecimal
价值相等但比例不同的对象(例如2.0 和2.00)被此方法视为相等.提供此方法 优先于六个布尔值中的每个布尔值的单个方法 比较运算符(< ;、 ==,>,> =,!=,< =).建议的成语 执行这些比较的是:(x.compareTo(y) <op> 0)
,其中<op>
是六个比较运算符之一.
Two BigDecimal
objects that are equal in value but have a different scale (like 2.0 and 2.00) are considered equal by this method. This method is provided in preference to individual methods for each of the six boolean comparison operators (<, ==, >, >=, !=, <=). The suggested idiom for performing these comparisons is: (x.compareTo(y) <op> 0)
, where <op>
is one of the six comparison operators.
返回: -1、0或1,因为此BigDecimal在数值上小于,等于或大于val.
Returns: -1, 0, or 1 as this BigDecimal is numerically less than, equal to, or greater than val.
这篇关于如何使用比较运算符,例如>,=,<在BigDecimal上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!