jdk工具类____bigdecimal精度运算工具类
package com.cctin.platform.util;
import java.math.BigDecimal;
public class MathUtil {
/**
* @info:加法运算
*/
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();
}
/**
* @info:减法运算
*/
public static double subtract(double v1, double v2) {
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.subtract(b2).doubleValue();
}
/**
* @info:乘法运算
*/
public static double multiply(double v1, double v2,int scale) {
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.multiply(b2).doubleValue();
}
/**
* @info:除法运算
* 除不尽保留
*/
public static double divide(double v1, double v2) {
//默认采用保留10位小数
int DEF_DIV_SCALE = 10;
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.divide(b2, DEF_DIV_SCALE, BigDecimal.ROUND_HALF_UP).doubleValue();
}
/**
* @info:精度运算 :四舍五入
*/
public static double accuracyRoundHalfUp(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();
}
/**
* @info:精度运算 :四舍五入
*/
public static double accuracyRoundDown(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_DOWN).doubleValue();
}
//======================test==================\\
public static void main(String[] args) {
//1.加法计算
System.out.println("加法计算____:"+add(2, 3.9));
//2.减法计算
System.out.println("加法计算____:"+subtract(2.67,1.67));
//3.乘法计算保留2位小数
System.out.println("乘法计算____:"+multiply(2.3, 4.56, 2));
//4.除法运算
System.out.println("除法运算____:"+divide(6.67, 2.1));
//5.精度运算:四舍五入
System.out.println("精度_四舍五入_:"+accuracyRoundHalfUp(3.349, 2));
//6.精度运算:直接舍去
System.out.println("精度_直接舍去_:"+accuracyRoundDown(3.349, 2));
}
}
//运行结果