Java BigDecimal and double

Source: Internet
Author: User

BigDecimal class

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. The common methods of the BigDecimal class are shown in the table.

Common methods of BigDecimal class

Serial number

Method

Type

Description

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

Example: Arithmetic for rounding

1  Packagecom.wy.test;2 3 ImportJava.math.BigDecimal;4 5  Public classBigdecimaltest {6      Public Static DoubleAddDoubleD1,DoubleD2) {//perform addition operations7BigDecimal B1 =NewBigDecimal (d1);8BigDecimal B2 =NewBigDecimal (D2);9         returnB1.add (B2). Doublevalue ();Ten     } One  A      Public Static DoubleSubDoubleD1,DoubleD2) {//perform the subtraction operation -BigDecimal B1 =NewBigDecimal (d1); -BigDecimal B2 =NewBigDecimal (D2); the         returnb1.subtract (B2). Doublevalue (); -     } -  -      Public Static DoubleMulDoubleD1,DoubleD2) {//Perform multiplication operations +BigDecimal B1 =NewBigDecimal (d1); -BigDecimal B2 =NewBigDecimal (D2); +         returnb1.multiply (B2). Doublevalue (); A     } at  -      Public Static DoubleDivDoubleD1,DoubleD2,intLen) {//Perform division operations -BigDecimal B1 =NewBigDecimal (d1); -BigDecimal B2 =NewBigDecimal (D2); -         returnb1.divide (B2, Len, bigdecimal.round_half_up). Doublevalue (); -     } in  -      Public Static DoubleRoundDoubleDintLen) {//Rounding Operations toBigDecimal B1 =NewBigDecimal (d); +BigDecimal B2 =NewBigDecimal (1); -         //any number divided by 1 is the original number . the         //Round_half_up is a constant of bigdecimal that represents the rounding Operation *         returnb1.divide (B2, Len, bigdecimal.round_half_up). Doublevalue (); $     }Panax Notoginseng  -      Public Static voidMain (string[] args) { theSYSTEM.OUT.PRINTLN ("addition operation:" + round (Add (10.345, 3.333), 1)); +         //addition operation: 13.7 ASystem.out.println ("Multiplication:" + round (Mul (10.345, 3.333), 3)); the         //multiplication operation: 34.48 +SYSTEM.OUT.PRINTLN ("Division operation:" + div (10.345, 3.333, 3)); -         //Division operation: 3.104 $System.out.println ("Subtraction operation:" + round (sub (10.345, 3.333), 3)); $         //subtraction operation: 7.012 -     } -}

BigDecimal is a class in Java that represents an arbitrary precision floating-point number operation, and in BigDecimal, the Unscaledvaluex10-scale is used to represent a floating-point number. Where Unscaledvalue is a biginteger,scale is an int. From this point of view, BigDecimal can only identify finite decimals, but can represent a range of data far greater than double, in practical applications is basically enough.

Let's mention two accuracy questions:problem One: The BigDecimal accuracy problem
1System.out.println (NewBigDecimal (0.1). ToString ());//0.10000000000000000555111512312578270211815834045410156252System.out.println (NewBigDecimal ("0.1"). ToString ());//0.13System.out.println (NewBigDecimal (4Double.tostring (0.1000000000000000055511151231257827021181583404541015625)). toString ());//0.15System.out.println (NewBigDecimal (Double.tostring (0.1)). ToString ());//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, or 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", Therefore the number of the generated bigdecimal is also 0.1;Line Fourth: Based on the previous analysis, the fact that this line of code is equivalent to the third row.  Conclusion:1. If you want BigDecimal 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 according to your idea;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 an exception will be thrown. question two: Is it not to throw away the fractional part by forcing the double into int? 1 int x= (int) 1023.99999999999999; // 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.

So, forcing 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 (new//  1024x768//  4090000000000000// 1024x768

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).

Java BigDecimal and double

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.