我是靠谱客的博主 踏实硬币,这篇文章主要介绍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:

句法:

复制代码
1
2
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:

例:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// 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

输出量

复制代码
1
2
3
b_dec1.round(ma_co): 1321 b_dec2.round(ma_co): 100.3

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

最后

以上就是踏实硬币最近收集整理的关于Java BigDecimal round()方法与示例的全部内容,更多相关Java内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(103)

评论列表共有 0 条评论

立即
投稿
返回
顶部