标签:实例化 ide 实例 href 精确 comm alt multi 四舍五入
java.math.BigDecimal。BigDecimal一共有4个够造方法,让我先来看看其中的两种用法:
第一种:BigDecimal(double val)
Translates a double into a BigDecimal.
第二种:BigDecimal(String val)
Translates the String repre sentation of a BigDecimal into a BigDecimal.
使用BigDecimal要用String来够造,要做一个加法运算,需要先将两个浮点数转为String,然后够造成BigDecimal,在其中一个上调用add方法,传入另一个作为参数,然后把运算的结果(BigDecimal)再转换为浮点数。
public static double add(double v1,double v2)
public static double sub(double v1,double v2)
public static double mul(double v1,double v2)
public static double div(double v1,double v2)
public static double div(double v1,double v2,int scale)
public static double round(double v,int scale)
- 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();
- }
- };
精度计算的方法
标签:实例化 ide 实例 href 精确 comm alt multi 四舍五入
原文地址:http://www.cnblogs.com/daishiwen/p/7424143.html