如何使用比较运算符,例如>,=,<在BigDecimal上 [英] How to use comparison operators like >, =, < on BigDecimal

查看:76
本文介绍了如何使用比较运算符,例如>,=,<在BigDecimal上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个将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的每个对象都有一个方法

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.

运算符==<>等只能用于原始数据类型,例如intlongdouble或它们的包装器类,例如Integer.

The operators ==, <, > and so on can only be used on primitive data types like int, long, double or their wrapper classes like Integerand Double.

来自compareTo的文档:

将此BigDecimal与指定的BigDecimal进行比较.

Compares this BigDecimal with the specified BigDecimal.

两个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.

这篇关于如何使用比较运算符,例如&gt;,=,&lt;在BigDecimal上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆