BigDecimal如何比较大小
2016-01-26 21:16
357 查看
BigDecimal比较大小
这个类是java里精确计算的类,下面说一下两个BigDecimal对象大小,相等的判断
1 比较对象是否相等
一般的对象用equals,但是BigDecimal比较特殊,举个例子:
BigDecimal a=BigDecimal.valueOf(1.0);
BigDecimal b=BigDecimal.valueOf(1.000);
在现实中这两个数字是相等的,但是如果用
a.equals(b)结果是false;怎么不相等了呢?因为equals是比较内容,“1.0”和“1.000”当然不一样了
解决办法:
if(a.compareTo(b)==0) 结果是true
public int compareTo(BigDecimal val)
Compares this BigDecimal with the specified BigDecimal.
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.
Specified by:
compareTo in interface Comparable<BigDecimal>
Parameters:
val - BigDecimal to which this BigDecimal is to be compared.
Returns:
-1, 0, or 1 as this BigDecimal is numerically less than, equal to, or greater than val.
简单翻译:
结果是
-1 小于
0 等于
1 大于
这个类是java里精确计算的类,下面说一下两个BigDecimal对象大小,相等的判断
1 比较对象是否相等
一般的对象用equals,但是BigDecimal比较特殊,举个例子:
BigDecimal a=BigDecimal.valueOf(1.0);
BigDecimal b=BigDecimal.valueOf(1.000);
在现实中这两个数字是相等的,但是如果用
a.equals(b)结果是false;怎么不相等了呢?因为equals是比较内容,“1.0”和“1.000”当然不一样了
解决办法:
if(a.compareTo(b)==0) 结果是true
public static void main(String[] args) { BigDecimal a = BigDecimal.valueOf(1.0); BigDecimal b = BigDecimal.valueOf(1.000); if (a.compareTo(BigDecimal.ZERO) == 1) {//结果是true System.out.println("1"); } else { System.out.println("2"); } }
public int compareTo(BigDecimal val)
Compares this BigDecimal with the specified BigDecimal.
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.
Specified by:
compareTo in interface Comparable<BigDecimal>
Parameters:
val - BigDecimal to which this BigDecimal is to be compared.
Returns:
-1, 0, or 1 as this BigDecimal is numerically less than, equal to, or greater than val.
简单翻译:
结果是
-1 小于
0 等于
1 大于
相关文章推荐
- LeetCode Gray Code
- Vagrant (2) —— 基本安装与配置(下)
- Latex----实现latex中用\cite命令时候,出来的不是[1],[2], 而是 作者 年
- LeetCode Merge Sorted Array
- 《机房收费系统合作版》验收感受
- LINK:fatal error LNK1123: 转换到 COFF 期间失败: 文件无效或损坏
- js-Ajax与Comet
- 开开心心
- Ajax的使用
- CPP 1014 Fans数
- 二分查找的实现
- mysql数据库的安装与使用
- [Javascript] Task queue & Event loop.
- Spring MVC 之请求处理方法可接收参数(三)
- python 图像识别
- 网站管理之IIS怎样设置能实现同服务器上有多个不同域名的网站
- ZOJ-3879-Capture the Flag【模拟】【12th浙江省赛】
- redis的数据类型
- Android使用BitmapFactory.Options压缩图片解决加载大图片内存溢出
- Elasticsearch过滤与聚合的先后顺序java实现