Java.math.BigDecimal.scale() Method

Description

The java.math.BigDecimal.scale() returns the scale of this BigDecimal. If zero or positive, the scale is the number of digits to the right of the decimal point.

If negative, the unscaled value of the number is multiplied by ten to the power of the negation of the scale. For example, a scale of -3 means the unscaled value is multiplied by 1000.

Declaration

Following is the declaration for java.math.BigDecimal.scale() method.

public int scale()

Parameters

NA

Return Value

This method returns the scale of this BigDecimal object.

Example

The following example shows the usage of math.BigDecimal.scale() method.

import java.math.*;

public class BigDecimalDemo {

    public static void main(String[] args) {

        // create 2 BigDecimal Objects
        BigDecimal bg1, bg2,bg3,bg4;
        //scale>=0,scale表示小数点后面的位数
        bg1 = new BigDecimal("123.0");
        bg2 = new BigDecimal("-1.123");
        bg3 = new BigDecimal("12345");
        bg4 = bg3.setScale(-2,BigDecimal.ROUND_HALF_UP);
        //scale<0,scale表示小数点后面的位数
// If negative, the unscaled value of the number is multiplied by ten to 
// the power of the negation of the scale. For example, a scale of -3 means the 
// unscaled value is multiplied by 1000.

        // create two int objects
        int i1,i2,i3,i4;

        // assign the result of scale on bg1, bg2 to i1,i2
        i1 = bg1.scale();
        i2 = bg2.scale();
        i3 = bg3.scale();
        i4 = bg4.scale();


        String str1 = "The scale of " + bg1 + " is " + i1;
        String str2 = "The scale of " + bg2 + " is " + i2;
        String str3 = "The scale of " + bg3 + " is " + i3;
        String str4 = "The scale of " + bg4.toString() + " is " + i4;


        // print the values of i1,i2;
        System.out.println( str1 );
        System.out.println( str2 );
        System.out.println( str3 );
        System.out.println( str4 );
    }
}
//result
The scale of 123.0 is 1
The scale of -1.123 is 3
The scale of 12345 is 0
The scale of 1.23E+4 is -2

参考:https://www.tutorialspoint.com/java/math/bigdecimal_scale.htm

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值