Java.math.BigDecimal.setScale() 方法



说明

java.math.BigDecimal.setScale(int newScale, RoundingMode roundingMode) 返回一个其标度为指定值的新 BigDecimal,且其未按比例缩放的值是由将该 BigDecimal 的未按比例缩放的值乘以或除以适当的 10 的幂来确定的,以便保持其总体值。

如果标度通过运算而减小,则必须除以(而不是乘以)未按比例缩放的值,且值可能会有所改变;在这种情况下,此指定的舍入模式适用于除法。

由于 BigDecimal 对象不可变,因此调用此方法不会导致修改原始对象,这与具有名为 setX 的方法(使字段 X 发生变异)的通常惯例相反。相反,setScale 会返回一个具有适当标度的对象;返回的对象可能是新分配的,也可能不是。

声明

以下是 java.math.BigDecimal.setScale() 方法的声明。

public BigDecimal setScale(int newScale, RoundingMode roundingMode)

参数

  • newScale − 要返回的 BigDecimal 值的标度。

  • roundingMode − 要应用的舍入模式。

返回值

此方法返回一个 BigDecimal 值,其标度为指定值,且其未按比例缩放的值是由将该 BigDecimal 的未按比例缩放的值乘以或除以适当的 10 的幂来确定的,以便保持其总体值。

异常

ArithmeticException − 如果 roundingMode == ROUND_UNNECESSARY 且指定的缩放运算需要进行舍入。

示例

以下示例演示了如何使用 math.BigDecimal.setScale() 方法。

package com.tutorialspoint;

import java.math.*;

public class BigDecimalDemo {

   public static void main(String[] args) {

      // create 2 BigDecimal Objects
      BigDecimal bg1, bg2;

      bg1 = new BigDecimal("123.12678");

      // set scale of bg1 to 2 in bg2 using floor as rounding mode
      bg2 = bg1.setScale(2, RoundingMode.FLOOR);

      String str = bg1 + " after changing the scale to 2 and rounding is " +bg2;

      // print bg2 value
      System.out.println( str );
   }
}

让我们编译并运行上述程序,将会产生以下结果:

123.12678 after changing the scale to 2 and rounding is 123.12
java_math_bigdecimal.htm
广告
© . All rights reserved.