Java BigDecimal round()方法与示例

BigDecimal类round()方法 (BigDecimal Class round() method)

  • round() method is available in java.math package.

    round()方法在java.math包中可用。

  • round() method is used to get a rounded BigDecimal based on the given MathContext setting when the precision value is not equal to 0 otherwise there is no effect of rounding when the precision value is equal to 0.

    当精度值不等于0时,使用round()方法基于给定的MathContext设置获取舍入的BigDecimal,否则,当精度值等于0时就没有舍入效果。

  • round() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.

    round()方法是一个非静态方法,只能通过类对象访问,如果尝试使用类名称访问该方法,则会收到错误消息。

  • round() method may throw an exception at the time of rounding.

    round()方法在四舍五入时可能会引发异常。

    ArithmeticException: This exception may throw when this BigDecimal need rounding and the mode of rounding is set to "UNNECESSARY".

    ArithmeticException :当此BigDecimal需要舍入并且舍入模式设置为“ UNNECESSARY”时,可能引发此异常。

Syntax:

句法:

    public BigDecimal round(MathContext ma_co);

Parameter(s):

参数:

  • MathContext ma_co – represents the MathContext to use in rounding BigDecimal.

    MathContext ma_co –表示四舍五入BigDecimal时使用的MathContext。

Return value:

返回值:

The return type of this method is BigDecimal, it returns the rounded BigDecimal based on the given MathContext.

此方法的返回类型为BigDecimal ,它根据给定的MathContext返回四舍五入的BigDecimal。

Example:

例:

// Java program to demonstrate the example 
// of BigDecimal round(MathContext ma_co) method of BigDecimal

import java.math.*;

public class RoundOfBD {
    public static void main(String args[]) {
        // Initialize two variables and
        // first is of "short" and second is  
        // of "String" type
        short val1 = 1321;
        String val2 = "100.24";

        // Initialize two BigDecimal objects and
        // one MathContext
        BigDecimal b_dec1 = new BigDecimal(val1);
        BigDecimal b_dec2 = new BigDecimal(val2);
        MathContext ma_co = new MathContext(4, RoundingMode.CEILING);


        // round this BigDecimal b_dec1 according to
        // the given MathContext based on precision
        // and rounding mode
        BigDecimal round = b_dec1.round(ma_co);
        System.out.println("b_dec1.round(ma_co): " + round);

        // round this BigDecimal b_dec1 according to
        // the given MathContext based on precision
        // and rounding mode
        round = b_dec2.round(ma_co);
        System.out.println("b_dec2.round(ma_co): " + round);
    }
}

Output

输出量

b_dec1.round(ma_co): 1321
b_dec2.round(ma_co): 100.3


翻译自: https://www.includehelp.com/java/bigdecimal-round-method-with-example.aspx

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值