Currency Amount-java in the BigDecimal

Source: Internet
Author: User

For numbers that do not require any accurate calculation accuracy, float or double can be used directly, but if you need to calculate the results accurately, you must use the BigDecimal class, and you can use the BigDecimal class for a large number of operations.

float and double can only be used for scientific calculations or engineering calculations, and in commercial calculations we have to use Java.math.BigDecimal.

Table 11-15 Common methods of BigDecimal class

Serial number

Square Method

Type

describe

1

Public BigDecimal (double val)

Structure

Convert a double representation

To BigDecimal

2

Public BigDecimal (int val)

Structure

Converts an int representation to a

BigDecimal

3

Public BigDecimal (String val)

Structure

Represents a String

Convert form to BigDecimal

4

Public BigDecimal Add (BigDecimal augend)

Ordinary

Addition

5

Public BigDecimal Subtract (BigDecimal
subtrahend)

Ordinary

Subtraction

6

Public BigDecimal Multiply (BigDecimal
Multiplicand)

Ordinary

Multiplication

7

Public BigDecimal Divide (BigDecimal
Divisor

Ordinary

Division

Calculation of BigDecimal

calculation of the amount BigDecimal classDoubleD =9.84;DoubleD2 =1.22;//Note You need to use the BigDecimal (String val) Construction methodBigDecimal BigDecimal =NewBigDecimal (double.tostring (d)); BigDecimal BigDecimal2=NewBigDecimal (double.tostring (D2));//additionBigDecimal Bigdecimaladd =Bigdecimal.add (bigDecimal2);DoubleAdd =Bigdecimaladd.doublevalue ();//SubtractionBigDecimal bigdecimalsubtract =bigdecimal.subtract (bigDecimal2);DoubleSubtract =Bigdecimalsubtract.doublevalue ();//multiplicationBigDecimal bigdecimalmultiply =bigdecimal.multiply (bigDecimal2);DoubleMultiply =Bigdecimalmultiply.doublevalue ();//DivisionintScale =2;//Keep 2 decimal placesBigDecimal bigdecimaldivide =bigdecimal.divide (bigDecimal2, scale, bigdecimal.round_half_up);Doubledivide =Bigdecimaldivide.doublevalue ();//FormattingDoubleFormat =12343171.6;//get regular numeric formattingNumberFormat number =numberformat.getnumberinstance (); String Str= Number.format (format);//12,343,171.6//get integer numeric formatNumberFormat integer =numberformat.getintegerinstance (); Str= Integer.format (format);//If a decimal is rounded to an integer 12,343,172//Get currency numeric formatNumberFormat currency =numberformat.getcurrencyinstance (); Currency.setminimumfractiondigits (2);//sets the minimum number of digits allowed for the decimal portion of the count (if not enough to complement 0)Currency.setmaximumfractiondigits (4);//sets the maximum number of digits allowed for the number of decimal parts (if more than will be rounded)str = currency.format (format);//¥12,343,171.60//get the format for displaying percentagesNumberFormat percent =numberformat.getpercentinstance ();p ercent.setminimumfractiondigits (2);//sets the minimum number of digits allowed for the decimal portion of the count (if not enough to complement 0)Percent.setmaximumfractiondigits (3);//sets the maximum number of digits allowed for the number of decimal parts (if more than will be rounded)str = percent.format (format);//1,234,317,160.00%
Let's mention two accuracy questions:question one: BigDecimal's accuracy problem (a guy on StackOverflow asked a related question)
SYSTEM.OUT.PRINTLN (// 0.1000000000000000055511151231257827021181583404541015625system.out.println ( // 0.1system.out.println (new BigDecimal (double.tostring ( 0.1000000000000000055511151231257827021181583404541015625)). toString ()); // 0.1system.out.println (// 0.1         

Analyze the problem with the above code (the contents of the comment represent the output of this statement)

The first line: In fact, since the binary cannot accurately represent decimal decimal 0.1, but after the compiler reads the string "0.1", it must be converted to a double value of 8 bytes, so the compiler can use only one nearest value instead of 0.1, which is 0.1000000000000000055511151231257827021181583404541015625. Thus, at run time, the true value passed to the BigDecimal constructor is 0.1000000000000000055511151231257827021181583404541015625. Second line: BigDecimal can correctly convert the string into a truly accurate floating-point number. The third line: The problem is that Double.tostring uses a certain amount of precision to round the double and then output it. Yes. The double.tostring (0.1000000000000000055511151231257827021181583404541015625) output is actually "0.1", So the number of BigDecimal represented is also 0.1. Line four: Based on the previous analysis, the fact that this line of code is equivalent to the third line conclusion: 1. If you want BigDecimal to be able to accurately represent the value you want, be sure to use a string to represent the decimal and pass it to the BigDecimal constructor. 2. If you use double.tostring to convert a double into a string and then call BigDecimal (String), this is also not reliable, it does not necessarily work as you think. 3. If you are not very concerned about whether you are fully accurate and use BigDecimal (double), pay attention to the special case of the double itself, the specification of the double itself defines several specific double values (Infinite,-infinite,nan ), do not pass these values to BigDecimal, or you will throw an exception.question two: Is it not to throw away the fractional part by forcing the double into int?
int x= (/// x=1024 why? 

The reason is that the binary cannot accurately represent some decimal decimals, so the double value of 1023.99999999999999 after compilation becomes 1024.

Soforcing a double into int is really throwing away the fractional part, but the value you write in the code is not necessarily the true double value that the compiler generates. Verification Code:
Double d = 1023.99999999999999;  int x = (int) D; System.out.println (         //////

As mentioned above, BigDecimal can be accurately represented by a double, remember.

We can also print the binary form of D directly, according to IEEE 754, we can calculate the 0x4090000000000000= (1024).

Currency Amount-java in the BigDecimal

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.