zoukankan      html  css  js  c++  java
  • 解决double精度问题(加减乘除)。

    package com.karl.test;
    
    import java.math.BigDecimal;
    
    public class Arith {
        private static final int DEF_DIV_SCALE = 10;
    
        private Arith() {
        }
    
        public static double add(double v1, double v2) {
            BigDecimal b1 = new BigDecimal(Double.toString(v1));
            BigDecimal b2 = new BigDecimal(Double.toString(v2));
            return b1.add(b2).doubleValue();
        }
    
        public static double sub(double v1, double v2) {
            BigDecimal b1 = new BigDecimal(Double.toString(v1));
            BigDecimal b2 = new BigDecimal(Double.toString(v2));
            return b1.subtract(b2).doubleValue();
        }
    
        public static double mul(double v1, double v2) {
            BigDecimal b1 = new BigDecimal(Double.toString(v1));
            BigDecimal b2 = new BigDecimal(Double.toString(v2));
            return b1.multiply(b2).doubleValue();
        }
    
        public static double div(double v1, double v2) {
            return div(v1, v2, DEF_DIV_SCALE);
        }
    
        public static double div(double v1, double v2, int scale) {
            if (scale < 0) {
                throw new IllegalArgumentException("The scale must be a positive integer or zero");
            }
            BigDecimal b1 = new BigDecimal(Double.toString(v1));
            BigDecimal b2 = new BigDecimal(Double.toString(v2));
            return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
        }
    
        public static double round(double v, int scale) {
            if (scale < 0) {
                throw new IllegalArgumentException("The scale must be a positive integer or zero");
            }
            BigDecimal b = new BigDecimal(Double.toString(v));
            BigDecimal one = new BigDecimal("1");
            return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
        }
    }
  • 相关阅读:
    prototype属性
    mui 结束时间不能大于开始时间
    DOM方式操作元素属性
    用户输入数字,自动生成钱值
    isNaN函数,判断其参数是否为数字类型
    switch 循环
    淘宝下单高并发解决方案(转)
    NLog文章系列——如何配置NLog(转)
    使用Nlog记录日志到数据库
    NLog文章系列——如何配置NLog
  • 原文地址:https://www.cnblogs.com/zhonghan/p/3675759.html
Copyright © 2011-2022 走看看