现在的位置: 首页 > 综合 > 正文

有关JAVA BigDecimal的使用

2013年06月04日 ⁄ 综合 ⁄ 共 2110字 ⁄ 字号 评论关闭

先看段官方文档

[java] view
plain
copy

  1. /*The results of thisconstructor can be somewhat unpredictable. One might assume that  
  2. new BigDecimal(.1) is exactlyequal to .1, but it is actually equal  
  3. to.1000000000000000055511151231257827021181583404541015625. This is so because.1  
  4. cannot be represented exactlyas a double (or, for that matter, as a binary fraction  
  5. of any finite length). Thus,the long value that is being passed in to the constructor  
  6. is not exactly equal to .1,appearances nonwithstanding. 
  7. The (String) constructor, onthe other hand, is perfectly predictable: new BigDecimal 
  8. (".1") is exactlyequal to .1, as one would expect. Therefore, it is generally  
  9. recommended that the (String)constructor be used in preference to this one.*/   

 

也就是说利用double作为参数的构造函数,无法精确构造一个BigDecimal对象,需要自己指定一个上下文的环境,也就是指定精确位。而利用String对象作为参数传入的构造函数能精确的构造出一个BigDecimal对象。

               

[java] view
plain
copy

  1. BigDecimal b = newBigDecimal("0.3");  //BigDecimal b = new BigDecimal(0.3);      
  2.                System.out.println(b.multiply(BigDecimal.valueOf(100)));  
  3.                System.out.println(b.floatValue()*100);  
  4.                System.out.println(b.multiply(BigDecimal.valueOf(100)).setScale(0,BigDecimal.ROUND_HALF_UP));  

 

关于setScale函数的:

setScale(1)表示保留以为小数,默认用四舍五入方式

setScale(1,BigDecimal.ROUND_DOWN)直接删除多余的小数位,如2.35会变成2.3

setScale(1,BigDecimal.ROUND_UP)进位处理,2.35变成2.4

setScale(1,BigDecimal.ROUND_HALF_UP)四舍五入,2.35变成2.4

setScaler(1,BigDecimal.ROUND_HALF_DOWN)五舍六入,2.35变成2.3,2.36变成2.40 如果是5则向下舍

关于类型转换:

BigDecimal类提供了诸如intValue(),floatValue(), doubleValue(), longValue()方法来将BigDecimal对象转换成对应的值

还提供了valueOf() 来将float,double类型转换为BigDecimal

 

网上总结:

1、此构造方法的结果有一定的不可预知性。有人可能认为在 Java 中写入 new BigDecimal(0.1) 所创建的 BigDecimal 正好等于 0.1(非标度值 1,其标度为 1),但是它实际上等于0.1000000000000000055511151231257827021181583404541015625。这是因为 0.1 无法准确地表示为double(或者说对于该情况,不能表示为任何有限长度的二进制小数)。这样,传入到构造方法的值不会正好等于 0.1(虽然表面上等于该值)。

2、另一方面,String 构造方法是完全可预知的:写入 new BigDecimal("0.1") 将创建一个BigDecimal,它正好等于预期的 0.1。因此,比较而言,通常建议优先使用 String 构造方法。

3、当 double 必须用作BigDecimal 的源时,请注意,此构造方法提供了一个准确转换;它不提供与以下操作相同的结果:先使用 Double.toString(double) 方法,然后使用BigDecimal(String) 构造方法,将 double 转换为 String。要获取该结果,请使用 static valueOf(double) 方法

抱歉!评论已关闭.