zoukankan      html  css  js  c++  java
  • java中的精度问题的处理

    精度问题在商业计算中非常重要,比如价格计算,概率计算,java在处理精度问题时可以使用BigDecimal类,详细见以下代码

     1 import java.math.BigDecimal;
     2 
     3 
     4 public class BigDecimalUtil {
     5     
     6     public static void main(String[] args) {
     7         System.out.println(0.05+0.01);//输出 : 0.060000000000000005
     8         //假设两件商品中价格是0.05 0.01  从输出结果中可以看出  那么0.06元是买不了这两件商品的
     9         System.out.println(0.06==(0.05+0.01));//输出 : false
    10         System.out.println(1-0.42);//输出 : 0.5800000000000001
    11         System.out.println(4.015*100);//输出 : 401.49999999999994 
    12         System.out.println(123.3/100);//输出 :1.2329999999999999
    13         System.out.println(add(0.05, 0.01).doubleValue()==0.06);//输出 :true
    14         sub(1D, 0.42);
    15         multiply(4.015, 100D);
    16         divide(123.3, 100D);
    17     }
    18     
    19     public static BigDecimal add(Double d1 , Double d2) {
    20         BigDecimal b1  = new BigDecimal(d1.toString());//一定要使用String 的构造器 否则会丢失精度
    21         BigDecimal b2  = new BigDecimal(d2.toString());
    22         return b1.add(b2);
    23     }
    24     
    25     public static BigDecimal sub(Double d1 , Double d2) {
    26         BigDecimal b1  = new BigDecimal(d1.toString());
    27         BigDecimal b2  = new BigDecimal(d2.toString());
    28         return b1.subtract(b2);
    29     }
    30     public static BigDecimal multiply(Double d1 , Double d2) {
    31         BigDecimal b1  = new BigDecimal(d1.toString());
    32         BigDecimal b2  = new BigDecimal(d2.toString());
    33         return b1.multiply(b2);
    34     }
    35     public static BigDecimal divide(Double d1 , Double d2) {
    36         BigDecimal b1  = new BigDecimal(d1.toString());
    37         BigDecimal b2  = new BigDecimal(d2.toString());
    38         return b1.divide(b2,2,BigDecimal.ROUND_HALF_UP);//这里是四舍五入 并且保留X位小数 默认两位
    39     }
    40 }
  • 相关阅读:
    Shell特殊变量:Shell $0, $#, $*, $@, $?, $$和命令行参数
    linux命令学习7-jstat命令
    linux命令学习6-dpkg命令
    PSSH 批量管理服务器
    堆排序 (Heap Sort)
    极客时间-左耳听风-程序员攻略-程序员修养
    应急响应-GHO提取注册表快照
    nc替代技术方案
    从无文件技术到使用隐写术:检查Powload的演变
    CVE-2019-0797漏洞:Windows操作系统中的新零日在攻击中被利用
  • 原文地址:https://www.cnblogs.com/tjqBlog/p/9395527.html
Copyright © 2011-2022 走看看