Java BigDecimal

Java BigDecimal class is used to deal with financial data. BigDecimal is preferred while dealing with high-precision arithmetic or situations that require more granular control over rounding off calculations.

Java BigDecimal类用于处理财务数据。 在处理高精度算术或需要对舍入计算进行更精细控制的情况下,首选BigDecimal。

Java BigDecimal (Java BigDecimal)

BigDecimals are Immutable, arbitrary-precision signed decimal numbers. Java BigDecimal class is defined in java.math package. Here is the BigDecimal class hierarchy:

BigDecimals是不可变的,任意精度的带符号十进制数字。 Java BigDecimal类在java.math包中定义。 这是BigDecimal类的层次结构:

Java BigDecimal also provides us convenient control over scale and precision. Before we explore BigDecimal class, we’ll briefly discuss precision and scale.

Java BigDecimal还为我们提供了对比例和精度的便捷控制。 在探索BigDecimal类之前,我们将简要讨论精度和小数位数。

Java BigDecimal精度和小数位数 (Java BigDecimal Precision and Scale)

By Definition, precision indicates the length of arbitrary precision integer whereas scale means the number of digits to the right of the decimal point. For example if we have a number “100.25” then precision is 5 because we need five digits to write down this number and scale is 2.

按照定义,精度表示任意精度整数的长度,而小数位数表示小数点右边的位数。 例如,如果我们有一个数字“ 100.25”,则精度为5,因为我们需要五位数字来记下该数字,小数位数为2。

We’ll look at some examples to get the clear idea about precision and scale.

我们将看一些示例,以获取有关精度和比例的清晰概念。

9999/10000 = 0.9999, scale = 4 and precision = 4
1/1000 = 0.0001, scale = 4 and precision = 1
0.000, special case and precision = 1

We can set scale for any BigInteger with constructors as well as methods available in the API. For now, let’s see how it effects the number:

我们可以使用构造函数以及API中可用的方法为任何BigInteger设置比例。 现在,让我们看看它如何影响数字:

9999 with scale 4 = 0.9999
9999 with scale 1 = 999.9 
9999 with scale -1 = 99990

We can clearly see that number gets multiplied by 10^-scale.

我们可以清楚地看到数字乘以10^-scale

Java BigDecimal构造函数 (Java BigDecimal Constructors)

There are several ways to create BigDecimal objects in Java. We’ll explore the constructors with code examples.

有几种方法可以用Java创建BigDecimal对象。 我们将通过代码示例探索构造函数。

  1. BigDecimal(BigInteger val): It takes BigInteger as an argument and creates a BigDecimal Object out of it.
    BigInteger bigInt = new BigInteger("233233233233");
    BigDecimal bigDecimal = new BigDecimal(bigInt);

    Similarly, there are constructors available in the class which accept int, double, long, char[] as well as String as an argument to create BigDecimal object:

    BigDecimal(BigInteger val) :它将BigInteger作为参数并从中创建一个BigDecimal对象。
    BigInteger bigInt = new BigInteger("233233233233");
    BigDecimal bigDecimal = new BigDecimal(bigInt);

    类似地,该类中有可用的构造函数,它们接受int,double,long,char []以及String作为创建BigDecimal对象的参数:

  2. BigDecimal(BigInteger unscaledVal, int scale): We can also provide scale along with the value while creating the object.
    BigInteger bigInt = new BigInteger("233233233233");
    int scale = 2;
    BigDecimal bigDecimal = new BigDecimal(bigInt, scale);
    System.out.println(bigDecimal);

    Output:

    BigDecimal(BigInteger unscaledVal, int scale) :在创建对象时,我们还可以提供比例尺和值。
    BigInteger bigInt = new BigInteger("233233233233");
    int scale = 2;
    BigDecimal bigDecimal = new BigDecimal(bigInt, scale);
    System.out.println(bigDecimal);

    输出:

  3. BigDecimal(BigInteger val, MathContext mc): It also gives us control to provide MathContext instance while creating the object.
    Basically, it provides precision matching IEEE 754R Format. Following are the possible values for java.math.MathContext:
    1. MathContext.DECIMAL128 ? to provide precision of 34 digits.
    2. MathContext.DECIMAL64 – to provide precision of 16 digits.
    3. MathContext.DECIMAL32 ? to provide precision of 7 digits.
    4. MathContext.UNLIMITED ? to provide unlimited precision.

    Let’s look at the code:

    BigInteger bigInt = new BigInteger("233233233233");
    BigDecimal bigDecimal = new BigDecimal(bigInt, MathContext.DECIMAL32);

    Ofcourse, it also provides similar constructors for int, long, double, char[] as well as String.

    BigDecimal(BigInteger val, MathContext mc) :它也使我们能够控制在创建对象时提供MathContext实例。
    基本上,它提供精确匹配的IEEE 754R格式。 以下是java.math.MathContext的可能值:
    1. MathContext.DECIMAL128吗? 提供34位数字的精度。
    2. MathContext.DECIMAL64 –提供16位数字的精度。
    3. MathContext.DECIMAL32吗? 提供7位数的精度。
    4. MathContext.UNLIMITED? 提供无限的精度。

    让我们看一下代码:

    当然,它也为int,long,double,char []和String提供了类似的构造函数。

  4. BigDecimal(BigInteger unscaledVal, int scale, MathContext mc): we can provide both scale and precision at the time of construction of an object.
    BigInteger bigInt = new BigInteger("233233233233");
    int scale = 2;
    BigDecimal bigDecimal = new BigDecimal(bigInt, scale,MathContext.DECIMAL32);

    BigDecimal(BigInteger unscaledVal, int scale, MathContext mc) :我们可以在构造对象时同时提供比例和精度。

Java BigDecimal方法 (Java BigDecimal Methods)

Java BigDecimal class provides us with several method to perform arithmatic operations, scale manipulation, rounding, comparision and formatting.

Java BigDecimal类为我们提供了几种执行算术运算,缩放操作,舍入,比较和格式化的方法。

Note that we can’t use operators such as +, – with it as they are not overloaded for the class. Instead, it provides respective methods to achieve the results.
Let’s look at the methods provided in the BigDecimal API with examples:

请注意,我们不能使用+等运算符,因为它们不会在类中重载。 相反,它提供了实现结果的相应方法。
让我们用示例看一下BigDecimal API中提供的方法:

  1. BigDecimal add(BigDecimal bigDecimal2): Returns a BigDecimal whose value is addition of this and bigDecimal2.
    BigInteger bigInt = new BigInteger("233233233233");
    int scale = 2;
    BigDecimal bigDecimal = new BigDecimal(bigInt, scale);
    BigDecimal bigDecimal2 = new BigDecimal(55662.3);
    System.out.println(bigDecimal.add(bigDecimal2));

    As you can see, returned object from add() method has scale which is max(this.scale, bigDecimal2). In our case, bigDecimal2 is created with the double and takes the scale value from it.
    There is also an overloaded add(BigDecimal bigDecimal2, MathContext mc) method which takes precision as argument and returns a BigDecimal object with rounding according to context settings.

    BigDecimal add(BigDecimal bigDecimal2) :返回一个BigDecimal,其值是thisbigDecimal2和。
    BigInteger bigInt = new BigInteger("233233233233");
    int scale = 2;
    BigDecimal bigDecimal = new BigDecimal(bigInt, scale);
    BigDecimal bigDecimal2 = new BigDecimal(55662.3);
    System.out.println(bigDecimal.add(bigDecimal2));

    如您所见,从add()方法返回的对象的比例尺为max(this.scale,bigDecimal2)。 在我们的示例中,bigDecimal2是使用double创建的,并从中获取了比例值。
    还有一个重载的add(BigDecimal bigDecimal2, MathContext mc)方法,该方法将precision作为参数并返回一个BigDecimal对象,并根据上下文设置进行舍入。

  2. BigDecimal subtract(BigDecimal bigDecimal2): Returns a BigDecimal whose value is subtraction of this and bigDecimal2.
    Similar to add() method, it also has privision to provide MathContext instance.
    System.out.println(bigDecimal.subtract(bigDecimal2));
    2332276670.029999999997089616954326629638671875

    BigDecimal subtract(BigDecimal bigDecimal2) :返回一个BigDecimal,其值是与thisbigDecimal2减法。
    与add()方法类似,它也具有提供MathContext实例的优先权。
  3. BigDecimal setScale(int newScale, RoundingMode roundingMode): A very Convinient and powerful method which allows us to set scale as well as rounding mode of the object. We already discussed scale. Let’s briefly discuss rounding mode and its possible values:
    An enum RoundingMode provides following possible rounding:
    1. UP: to round away from zero
    2. CEILING: to round towards positive infinity
    3. DOWN: to round towards zero
    4. FLOOR: to round towards negative infinity
    5. HALF_DOWN: to round towards “nearest neighbor” unless both neighbors are equidistant, in which case round down
    6. HALF_EVEN: to round towards the “nearest neighbor” unless both neighbors are equidistant, in which case, round towards the even neighbor
    7. HALF_UP: to round towards “nearest neighbor” unless both neighbors are equidistant, in which case round up
    8. UNNECESSARY: to assert that the requested operation has an exact result, hence no rounding is necessary
    BigDecimal bigDecimal = new BigDecimal("23323323.3533");
    System.out.println(bigDecimal);
    System.out.println("CEILING: "+bigDecimal.setScale(2,RoundingMode.CEILING));
    System.out.println("DOWN: "+bigDecimal.setScale(2,RoundingMode.DOWN));
    System.out.println("FLOOR: "+bigDecimal.setScale(2,RoundingMode.FLOOR));

    Output:

    BigDecimal setScale(int newScale, RoundingMode roundingMode) :一种非常便捷而强大的方法,它使我们可以设置对象的缩放比例和舍入模式。 我们已经讨论过规模。 让我们简要讨论舍入模式及其可能的值:
    枚举RoundingMode提供以下可能的舍入:
    1. 上:从零舍入
    2. 上限:朝正无穷大方向取
    3. 下:向零舍入
    4. 地板:向负无穷大方向舍入
    5. HALF_DOWN:朝着“最近的邻居”取整,除非两个邻居都等距,在这种情况下取​​整
    6. HALF_EVEN:向“最近的邻居”舍入,除非两个邻居都等距,在这种情况下,向“偶数邻居”舍入
    7. HALF_UP:朝着“最近的邻居”取整,除非两个邻居都等距,在这种情况下取​​整
    8. 不必要:断言所请求的操作具有准确的结果,因此无需四舍五入
    BigDecimal bigDecimal = new BigDecimal("23323323.3533");
    System.out.println(bigDecimal);
    System.out.println("CEILING: "+bigDecimal.setScale(2,RoundingMode.CEILING));
    System.out.println("DOWN: "+bigDecimal.setScale(2,RoundingMode.DOWN));
    System.out.println("FLOOR: "+bigDecimal.setScale(2,RoundingMode.FLOOR));

    输出:

  4. BigInteger unscaledValue(): We can also get unscaled values at any point of time.
    For Example, following code:
    BigDecimal bigDecimal = new BigDecimal("23323323.3533");
    System.out.println(bigDecimal);
    System.out.println(bigDecimal.unscaledValue());

    will get us:

    there is also scale() method which returns scale of the BigDecimal object

    BigInteger unscaledValue() :我们还可以在任何时间获取未缩放的值。
    例如,以下代码:
    BigDecimal bigDecimal = new BigDecimal("23323323.3533");
    System.out.println(bigDecimal);
    System.out.println(bigDecimal.unscaledValue());

    将使我们:

    还有scale()方法可返回BigDecimal对象的scale

  5. BigDecimal divide(BigDecimal divisor, int roundingMode): Computes division of this and divisor and returns the output with provided roundingMode.

    BigDecimal divide(BigDecimal divisor, int roundingMode) :计算this divisordivisor并使用提供的roundingMode返回输出。
  6. BigDecimal divide(BigDecimal divisor, int scale, int roundingMode): Computes division of this and divisor and returns the output with provided roundingMode and scale.

    BigDecimal divide(BigDecimal divisor, int scale, int roundingMode) :计算thisdivisor并返回具有提供的roundingMode和scale的输出。
  7. BigDecimal multiply(BigDecimal multiplicand): Computes multiplication of this and multiplicand and returns the output.

    BigDecimal multiply(BigDecimal multiplicand) :计算this multiplicand和被乘数的multiplicand并返回输出。
  8. BigDecimal pow(int n): Returns a BigDecimal whose value is (this^n), The power is computed exactly, to unlimited precision.

    BigDecimal pow(int n) :返回一个BigDecimal,其值为(this ^ n)。精确地计算出功效,达到无限精度。

Note that for each operator method, there is an overloaded method which accepts MathContext object and returns the output with respective precision.

请注意,对于每个运算符方法,都有一个重载方法,该方法接受MathContext对象并以各自的精度返回输出。

Java BigDecimal示例 (Java BigDecimal Example)

Now, let’s have a look at an example to check out above java BigDecimal methods:

现在,让我们看一个示例来检查上面的Java BigDecimal方法:

BigDecimal bigDecimal = new BigDecimal("2255223");
BigDecimal bigDecimal2 = new BigDecimal("55662.3");
System.out.println("Division by specifying rounding mode: " + bigDecimal.divide(bigDecimal2, RoundingMode.CEILING));
System.out.println("Division by specifying scale and rounding mode: "+ bigDecimal.divide(bigDecimal2, 2, RoundingMode.CEILING));
System.out.println("Multiplication: "+bigDecimal.multiply(bigDecimal2));
System.out.println("Power: "+bigDecimal.pow(2));

Output:

输出:

Division by specifying rounding mode: 41
Division by specifying scale and rounding mode: 40.52
Multiplication: 125530899192.9
Power: 5086030779729

There are many methods provided in the BigDecimal class for various operators such as min(), max(). Also, it provides with methods such as intValue(), doubleValue(), longValue() to get output in required format.

BigDecimal类提供了许多用于各种运算符的方法,例如min()max() 。 此外,它还提供了诸如intValue()doubleValue()longValue()来获取所需格式的输出。

Java BigDecimal格式 (Java BigDecimal Formatting)

We can use the api along with java.text.NumberFormat to apply desired formatting to the big numbers. For instance, let’s say we want to print the amount in USD:

我们可以将api与java.text.NumberFormat一起使用,以将所需的格式应用于大数字。 例如,假设我们要以美元打印金额:

BigDecimal bigDecimal = new BigDecimal("225522333333");
System.out.println("Unformatted: " + bigDecimal.toString());
NumberFormat n = NumberFormat.getCurrencyInstance(Locale.US);
double money = bigDecimal.doubleValue();
String s = n.format(money);
System.out.println("Formatted: "+s);

Output:

输出:

Unformatted: 225522333333
Formatted: $225,522,333,333.00

Java BigDecimal compareTo (Java BigDecimal compareTo)

Java BigDecimal class implements Comparable interface and we should use it’s compareTo method to compare two BigDecimal objects.

Java BigDecimal类实现Comparable接口,我们应该使用它的compareTo方法比较两个BigDecimal对象。

Note that two BigDecimal objects that are equal in value but have a different scale (like 10.0 and 10.00) are considered equal by compareTo method.

请注意,用compareTo方法将值相等但规模不同(例如10.0和10.00)的两个BigDecimal对象视为相等。

BigDecimal bd1 = new BigDecimal("100");
BigDecimal bd2 = new BigDecimal("100.00");
BigDecimal bd3 = new BigDecimal("50");
BigDecimal bd4 = new BigDecimal("200");

System.out.println("100 compareTo 100.00 = "+bd1.compareTo(bd2));
System.out.println("100 compareTo 50 = "+bd1.compareTo(bd3));
System.out.println("100 compareTo 200 = "+bd1.compareTo(bd4));

Output of above BigDecimal compareTo example code is:

以上BigDecimal compareTo示例代码的输出是:

100 compareTo 100.00 = 0
100 compareTo 50 = 1
100 compareTo 200 = -1

Java BigDecimal toString (Java BigDecimal toString)

Java BigDecimal toString method behaves differently based on the scale value. If the scale is 6 or more, then it prints in exponential notation. Below are some pseudo code to show the BigDecimal value with scale and the String representation returned by toString method.

Java BigDecimal toString方法根据比例值的不同而表现不同。 如果比例尺为6或更大,则以指数符号打印。 以下是一些伪代码,用于显示具有刻度的BigDecimal值以及toString方法返回的String表示形式。

[456,0]      "456"
 [-456,0]     "-456"
 [456,-1]     "4.56E+3"
 [456,-3]     "4.56E+5"
 [456,1]      "45.6"
 [456,5]      "0.00456"
 [456,10]     "4.56E-8"
 [-456,12]    "-4.56E-10"

Here is a simple java example for BigDecimal toString example.

这是BigDecimal toString示例的简单Java示例。

BigDecimal bd1 = new BigDecimal(new BigInteger("10"),10);
System.out.println("BigDecimal(10) with Scale 10 toString = "+bd1);

bd1 = new BigDecimal(new BigInteger("10"),4);
System.out.println("BigDecimal(10) with Scale 4 toString = "+bd1);

Output produced by above BigDecimal toString example code is:

上面的BigDecimal toString示例代码产生的输出是:

BigDecimal(10) with Scale 10 toString = 1.0E-9
BigDecimal(10) with Scale 4 toString = 0.0010

That’s all for Java BigDecimal class.

这就是Java BigDecimal类的全部内容。

Reference: API Doc

参考: API文档

翻译自: https://www.journaldev.com/16409/java-bigdecimal

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值