Math类中的BigDecimal

如果我们编译运行下面这个程序会看到什么?

public class Test {
    public static void main(String args[]) {
        
        System.out.println(0.05 + 0.01);
        System.out.println(1.0 - 0.42);
        System.out.println(4.015 * 100);
        System.out.println(123.3 / 100);
        
    }
}

你没有看错!结果确实是

0.060000000000000005
0.5800000000000001
401.49999999999994
1.2329999999999999

Java中的简单浮点数类型float和double不能够进行运算。不光是Java,在其它很多编程语言中也有这样的问题。在大多数情况下,计算的结果是准确的,但是多试几次(可以做一个循环)就可以试出类似上面的错误。现在终于理解为什么要有BCD码了。
这个问题相当严重,如果你有9.999999999999元,你的计算机是不会认为你可以购买10元的商品的。
在有的编程语言中提供了专门的货币类型来处理这种情况,但是Java没有。现在让我们看看如何解决这个问题。

四舍五入
我们的第一个反应是做四舍五入。Math类中的round方法不能设置保留几位小数,我们只能象这样(保留两位):

public double round(double value) {
        return Math.round(value * 100) / 100.0;
    }

非常不幸,上面的代码并不能正常工作,给这个方法传入4.015它将返回4.01而不是4.02,如我们在上面看到的
4.015*100=401.49999999999994
因此如果我们要做到精确的四舍五入,不能利用简单类型做任何运算
java.text.DecimalFormat也不能解决这个问题:
System.out.println(new java.text.DecimalFormat("0.00").format(4.025));
输出是4.02

BigDecimal
在《Effective Java》这本书中也提到这个原则,float和double只能用来做科学计算或者是工程计算,在商业计算中我们要用java.math.BigDecimal。BigDecimal一共有4个够造方法,我们不关心用BigInteger来够造的那两个,那么还有两个,它们是:

BigDecimal(double val) 
          Translates a double into a BigDecimal. 
BigDecimal(String val) 
          Translates the String repre sentation of a BigDecimal into a BigDecimal.

上面的API简要描述相当的明确,而且通常情况下,上面的那一个使用起来要方便一些。我们可能想都不想就用上了,会有什么问题呢?等到出了问题的时候,才发现上面哪个够造方法的详细说明中有这么一段:
Note: the results of this constructor can be somewhat unpredictable. One might assume that new BigDecimal(.1) is exactly equal to .1, but it is actually equal to .1000000000000000055511151231257827021181583404541015625. This is so because .1 cannot be represented exactly as a double (or, for that matter, as a binary fraction of any finite length). Thus, the long value that is being passed in to the constructor is not exactly equal to .1, appearances nonwithstanding. 
The (String) constructor, on the other hand, is perfectly predictable: new BigDecimal(".1") is exactly equal to .1, as one would expect. Therefore, it is generally recommended that the (String) constructor be used in preference to this one.
原来我们如果需要精确计算,非要用String来够造BigDecimal不可!在《Effective Java》一书中的例子是用String来够造BigDecimal的,但是书上却没有强调这一点,这也许是一个小小的失误吧。

解决方案
现在我们已经可以解决这个问题了,原则是使用BigDecimal并且一定要用String来够造。
但是想像一下吧,如果我们要做一个加法运算,需要先将两个浮点数转为String,然后够造成BigDecimal,在其中一个上调用add方法,传入另一个作为参数,然后把运算的结果(BigDecimal)再转换为浮点数。你能够忍受这么烦琐的过程吗?下面我们提供一个工具类Arith来简化操作。它提供以下静态方法,包括加减乘除和四舍五入:
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)
附录
源文件Arith.java:

import java.math.BigDecimal;

public class Arith {
    //默认除法运算精度
    private static final int DEF_DIV_SCALE = 10;

//这个类不能实例化
    private Arith()
    {
        ;
    }
    /**
    * 提供精确的加法运算。
    * @param v1 被加数
    * @param v2 加数
    * @return 两个参数的和
    */
    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();
    }
    /**
    * 提供精确的减法运算。
    * @param v1 被减数
    * @param v2 减数
    * @return 两个参数的差
    */
    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();
    }
    /**
    * 提供精确的乘法运算。
    * @param v1 被乘数
    * @param v2 乘数
    * @return 两个参数的积
    */
    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();
    }
    /**
    * 提供(相对)精确的除法运算,当发生除不尽的情况时,精确到
    * 小数点以后10位,以后的数字四舍五入。
    * @param v1 被除数
    * @param v2 除数
    * @return 两个参数的商
    */
    public static double div(double v1,double v2)
    {
        return div(v1,v2,DEF_DIV_SCALE);
    }
    /**
    * 提供(相对)精确的除法运算。当发生除不尽的情况时,由scale参数指
    * 定精度,以后的数字四舍五入。
    * @param v1 被除数
    * @param v2 除数
    * @param scale 表示表示需要精确到小数点以后几位。
    * @return 两个参数的商
    */
    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();
    }
    /**
    * 提供精确的小数位四舍五入处理。
    * @param v 需要四舍五入的数字
    * @param scale 小数点后保留几位
    * @return 四舍五入后的结果
    */
    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();
    }
}

Math类中的BigDecimal

时间: 2024-08-28 03:08:34

Math类中的BigDecimal的相关文章

Math类中round、ceil和floor方法的功能

Java中的Math工具类用来完成除+.-.*./.%等基本运算以外的复杂运算,位于java.lang包下,Math类的构造器全是私有的(private),因此无法创建Math类的对象,Math类的方法全是类方法,可以直接通过类名来调用它们.下面重点介绍Math类中经常用到的几个方法,也是面试时经常被问到的知识点. 1.round round方法表示四舍五入.round意为“环绕”,其原理是在原数字的基础上先加上0.5再向下取整,它的返回值为int类型,例如,Math.round(11.5)等于

Math类和BigInteger:/BigDecimal类

Math类:提供了简单计算的数学计算工具类 1:public static Xxx abs(Xxx xx)  求绝对值 2:public static double ceil(double a)  天花板  向上取整 3:public static double floor(double a)  地板  向下取整 4:public static double pow(double a, double b)  a^b  第一个数的第二个数次幂 5:public static double rand

Math类中的取整方法

Math类提供了3个有关取整的方法:ceil().floor().round(). 这些方法与他们的英文名字相对应: ceil,天花板,意思就是向上取整,Math.ceil(11.5)的结果为12,Math.ceil(-11.5)的结果为-11. floor,地板,意思就是向下取整,Math.floor(11.5)的结果为11,Math.floor(-11.5)的结果为-12. round,表示四舍五入,算法为:Math.floor(x+0.5), 即将原来的数字加上0.5后在向下取整,Math

Java Math 类中的新功能--浮点数

Java™语言规范第 5 版向 java.lang.Math和 java.lang.StrictMath添加了 10 种新方法,Java 6 又添加了 10 种.这个共两部分的系列文章的 第 1 部分介绍了很有意义的新的数学方法.它提供了在还未出现计算机的时代中数学家比较熟悉的函数.在第 2 部分中,我主要关注这样一些函数,它们的目的是操作浮点数,而不是抽象实数. 就像我在 第 1 部分中提到的一样,实数(比如 e或 0.2)和它的计算机表示(比如 Java double)之间的区别是非常重要的

java 中的math类详解

math类包含完成基本数学函数所需的方法.这些方法基本可以分为三类:三角函数方法.指数函数方法和服务方法.在math类中定义了PI和E两个double型常量, PI就是π的值,而E即e指数底的值,分别是:3.141592653589793和2.718281828459045: 三角函数方法 math类包含下面的三角函数方法: Math.toDegrees这个方法是将-π/2到π/2之间的弧度值转化为度,例如:Math.toDegrees(Math.PI/2)结果为90.0: Math.toRad

Math类

java提供了基本的+,-,*,/算数运算符,同时也提供了更复杂的运算符,比如三角函数,对数元,指数运算 Math是一个工具类.它的构造器被定义为private,因此无法创建Math类的对象,Math类中的所有方法都是 类方法,可以直接通过类名来调用,Math除了提供了大量的静态方法,还提供了两个类变量PI和E public class MathTest{ public static void main(String[] args){ //将弧度转化成角度 System.out.println(

Math类概述及其成员方法

Math 类包括用于运行基本数学运算的方法,如初等指数.对数.平方根和三角函数,这个类寻常开发中用的不多,可是在某些需求上会用到,比方求二个用户年龄的相差多少岁,这会用到Math类中的方法!如今把Maht几个经常使用的方法列举一下, public static int abs(int a) 求一个数的绝对值 public static double ceil(double a) 向上取大于这个数的最小整数 public static double floor(double a) 向下取这个值最大

JAVA API(三) Math类和Random类

1.Math类 Math类是数学操作类,提供了一些用于进行数学计算的静态方法.Math类中有两个静态常量PI和E,分别代表数学常量π和e. 列表中是Math类的一些常用方法: 方法声明 功能描述 int abs(int a) 计算a的绝对值 double ceil(double a) 向上取整,求大于参数的最小整数 double  floor(double a ) 向下取整,求小于参数的最大整数 long round(double a) 表示四舍五入,算法为Math.floor(a+0.5) d

Math类数据处理

在Math类中提供了众多数学函数方法,主要包括三角函数方法.指数函数方法.取整函数方法.取最大值.最小值以及平均值函数方法,这些方法都被定义为static形式,所以在程序中应用比较简便.可以使用如下形式调用: Math.数学方法 在Math类中除了函数方法之外还存在一些常用数学常量,如圆周率.E等.这些数学常量作为Math类的成员变量出现,调用起来也很简单.可以使用如下形式调用: Math.PI Math.E 在Math类中的常用数学运算方法较多,大致可以将其分为4大类别,分别为三角函数方法.指