BigDecimal How to use

Source: Internet
Author: User

BigDecimal How to use Blog Category:
    • Java Basics
The Bigdecimalmultiplyadddivide BigDecimal consists of an integer non-scaling value of arbitrary precision and a 32-bit integer scale (scales). If zero or positive, the scale is the number of digits after the decimal point. If it is negative, the non-scaling value of the number is multiplied by the 10 negative scale power. Therefore, the value represented by BigDecimal is (Unscaledvaluex10-scale).

You can handle floating-point arithmetic of any length.

BigDecimal Add (BigDecimal val)//bigdecimal addition

BigDecimal Subtract (BigDecimal val)//bigdecimal subtraction

BigDecimal Multiply (BigDecimal val)//bigdecimal multiplication

BigDecimal Divide (BigDecimal val,roundingmode mode) division


Specific usage calculations:


Add: A.add (b);

Minus: A.subtract (b);

By: A.multiply (b);

In addition to: A.divide (b,2);//2 Precision Value
Division Fine Solution:
Note that the following division throws an exception, because when you divide by the divide method of BigDecimal, an infinite loop of decimals occurs, and an exception is thrown.
BigDecimal DIVIDEBG = a.divide (b);
The workaround is to set the accuracy, which is to set the exact decimal point for the divide
Divide (xxxxx,2, Bigdecimal.round_half_even)
The second parameter indicates how many bits are left after the decimal point

BigDecimal do not divide the exception thrown, set the accuracy!
Exception in thread "main" java.lang.arithmeticexception:non-terminating decimal expansion; No exact representable decimal result.
At Java.math.BigDecimal.divide (bigdecimal.java:1278)
At Main. Main.main (main.java:41)

Let's take a look at the detailed description of division:
Divide (BigDecimal divisor, int scale, Introundingmode)


The Setscale method of BigDecimal

Bigdecimal.setscale ()

method is used to format the decimal point

Indicates that a decimal number is reserved and is rounded by default

Setscale (1)

Delete extra decimal digits directly, such as 2.35 will become 2.3 setscale (1,bigdecimal.round_down)

Carry handle, 2.35 becomes 2.4 setscale (1,BIGDECIMAL.ROUND_UP)

Rounded, 2.35 turned 2.4 setscale (1,BIGDECIMAL.ROUND_HALF_UP)

Rounding, 2.35 becomes 2.3, if 5 is down Setscaler (1,bigdecimal.round_half_down)


Attention, one.

Scale refers to the number of digits after your decimal point.
Scale () is the method in the BigDecimal class. Such as

BigDecimal B = new BigDecimal ("123.456");

B.scale () returned is 3.
Note that point two Roundingmode is a reserved mode for decimals. They are all constant fields in the BigDecimal,

There are many kinds, such as
Bigdecimal.round_half_up means 4, 5.

Note Three.

Divide (BigDecimal divisor, int scale, introundingmode) means that:
I used a BigDecimal object to divide the result after divisor, and asked the result to retain a scale decimal place, Roundingmode is what the retention pattern is, rounding, or something else.


BigDecimal AA = new BigDecimal (135.95);

BigDecimal bb=new BigDecimal ("100");

BigDecimal result=aa.multiply (BB); Do the addition



The BigDecimal type in 3.java can be converted to a double type:
Use variable. Doublevalue (); function to convert BigDecimal type data to double type!
4.java BigDecimal Comparison Size

Comparisons can be made by BigDecimal's CompareTo method.
The returned result is of type int, 1 means less than, 0 is equal, and 1 is greater than.

Look at the following example:
BigDecimal a = new BigDecimal ("1.00");
Bigdecmial B = new BigDecimal (1);

To compare the size of a and B, you will generally use equals

System.out.println (A.equals (b));
But the output is: false
The reason is: BigDecimal comparison, not only compare values, but also relatively accurate?


if (A.compareto (b) ==0) The result is true

Compare size can be used A.compareto (b)
return value-1 less than 0 equals 1 greater than

5.BigDecimal whichever is maximum, minimum, absolute, or opposite:

A.max (b)//Compare maximum

A.min (b)//Compare minimum values

A.abs ()//Take the absolute value

A.negate ()//Take the opposite number


6. Note the following:

BigDecimal enumeration Constants Usage Summary:

CEILING
Rounding mode rounded to the positive infinity direction.
Down
Rounding mode rounded to the 0 direction.
Floor
Rounding mode rounded to the negative infinity direction.
Half_down
Rounding mode rounded to the nearest number direction, rounded down if the distance to the two adjacent digits is equal.
Half_even
Rounding mode rounded to the nearest number direction, rounded to adjacent even if the distance to the two adjacent numbers is equal.
Half_up
Rounding mode rounded to the nearest number direction, rounded up if the distance to the two adjacent digits is equal.
Unnecessary
The operation used to assert the request has a rounding pattern with precise results, so no rounding is required.
Up
Rounding mode is rounded away from the 0 direction.



7. About BigDecimal Formatting

Public String Formatvalue (Object value) {
String content = null;
if (value = = null) {
Content = "";
} else {
if (value instanceof BigDecimal) {
Conver to Fortmat String
NumberFormat NF = numberformat.getinstance ();
Nf.setminimumfractiondigits (2);
Nf.setmaximumfractiondigits (2);
Content = Nf.format (value);
}else{
Content = string.valueof (value);
}
}
return content;
}

Using such a method can achieve the formatting effect, where value instanceof BigDecimal, that is, the character type is BigDecimal type of time to execute, here the NumberFormat represents the character type, The following two lines of code represent the exact number of digits after the decimal point.

There are two other types of NumberFormat mentioned here:

Getcurrencyinstance (): Returns the currency format of the current default environment

Currencyinstance (): Returns the number format for the specified locale, which is generally in percent format


8. This principle is also mentioned in the book effective Java, where float and double can only be used for scientific calculations or engineering calculations, and we use java.math.BigDecimal in business calculations.
If we need to calculate accurately, we must use string to build BigDecimal!

The following tool class is reproduced by others, you can use a tool class to achieve the precise calculation of decimals.

1import Java.math.BigDecimal;
2/** *//**
Because Java's simple type does not accurately operate on floating-point numbers, the tool class provides fine
The floating-point arithmetic, including subtraction and rounding.
5*/
6public class arith{
7//Default division operation accuracy
8 private static final int def_div_scale = 10;
9//This class cannot be instantiated
Private Arith () {
11}
12
13/** *//**
14 * Provides accurate addition operations.
* @param v1 Summand
* @param v2 Addend
* @return two parameters and
18 */
public static double Add (Double v1,double v2) {
BigDecimal B1 = new BigDecimal (double.tostring (v1));
BigDecimal b2 = new BigDecimal (double.tostring (v2));
B1.add return (B2). Doublevalue ();
23}
24/** *//**
25 * provides accurate subtraction operations.
* @param v1 minuend
V2 * @param meiosis
* @return The difference of two parameters
29 */
public static double sub (double v1,double v2) {
BigDecimal B1 = new BigDecimal (double.tostring (v1));
BigDecimal b2 = new BigDecimal (double.tostring (v2));
B1.subtract return (B2). Doublevalue ();
34}
35/** *//**
36 * provides accurate multiplication operations.
PNS * @param v1 by multiplier
* @param v2 Multiplier
Total * @return two parameters
40 */
The public static double Mul (Double v1,double v2) {
BigDecimal B1 = new BigDecimal (double.tostring (v1));
BigDecimal b2 = new BigDecimal (double.tostring (v2));
B1.multiply return (B2). Doublevalue ();
45}
46
47/** *//**
48 * Provide (relative) accurate division operation, when the occurrence of an endless situation, accurate to
49 * After the decimal point 10 digits, the later numbers are rounded.
* @param v1 Dividend
Wuyi * @param v2 Divisor
* @return Two-parameter quotient
53 */
The public static double div (Double v1,double v2) {
Return Div (V1,v2,def_div_scale);
56}
57
58/** *//**
59 * provides (relative) accurate division operations. When an exception occurs, the scale parameter refers to the
60 * Fixed precision, after which the number is rounded.
V1 * @param dividend
* @param v2 Divisor
The @param scale indicates the need to be accurate to several decimal places.
* @return two parameters of a quotient
65 */
v1,double public static Double div (double-v2,int scale) {
if (scale<0) {
The New IllegalArgumentException (
"The scale must is a positive integer or zero");
70}
BigDecimal B1 = new BigDecimal (double.tostring (v1));
BigDecimal b2 = new BigDecimal (double.tostring (v2));
B1.divid return (B2,SCALE,BIGDECIMAL.ROUND_HALF_UP). Doublevalue ();
74}
75
76/** *//**
77 * Provides precise rounding of decimal digits.
* @param v needs to be rounded to a number
* @param scale after decimal point retain several
Results after rounding @return
81 */
Round public static double V,int (double) {
if (scale<0) {
+ Throw New IllegalArgumentException (
"The scale must is a positive integer or zero");
86}
BigDecimal B = New BigDecimal (double.tostring (v));
BigDecimal one = new BigDecimal ("1");
B.divid return (ONE,SCALE,BIGDECIMAL.ROUND_HALF_UP). Doublevalue ();
90}
91}

BigDecimal How to use

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.