Java BigDecimal, javabigdecimal

Source: Internet
Author: User

Java BigDecimal, javabigdecimal

Java provides operation classes for big numbers, namely java. math. BinInteger and java. math. BigDecimal. These two classes are used for high-precision computing. The BigInteger class is a processing class for large integers, while the BigDecimal class is a processing class for large numbers.

BigDecimal

The implementation of BigDecimal utilizes BigInteger. The difference is that BigDecimal adds the concept of decimal. Generally, float and Double types of data can only be used for scientific or engineering computation. Because commercial computation requires a high digital accuracy, java is used. math. bigDecimal class, which supports any precision of the number of points, you can use it to accurately calculate the currency value. Below we will give an example to briefly introduce its usage.

Java. math. BigDecimal

1. BigInteger belongs to java. math. BigInteger. Therefore, you must import this class before each use. I forgot to import it at the beginning, so I was always prompted that the prompt could not be found.

2. There are many constructor methods, but now I am using the following methods:

BigInteger(String val)

Converts the decimal string representation of BigInteger to BigInteger.

BigInteger(String val, int radix)

Converts the string representation of the specified BigInteger to BigInteger.

To convert int type 2 to BigInteger type, write

BigInteger two = new BigInteger ("2"); // note that the double quotation marks cannot be omitted.

3. The BigInteger class simulates all int-type mathematical operations, such as add () = "+" and divide () =, however, when you perform mathematical operations on the content, you must use the internal method instead of the mathematical operators. The operands must also be BigInteger.

For example, two. add (2) is an incorrect operation because 2 has not changed to the BigInteger type.

4. Use the. toString method to convert the computation result to a decimal string. The details are as follows:

String toString()

Returns the decimal string representation of this BigInteger. Output method:

System.out.print(two.toString());

5. It also describes the three functions used.

BigInteger remainder(BigInteger val)

Return the BigInteger whose value is (this % val.

BigInteger negate()

Return the BigInteger whose value is (-this.

int compareTo(BigInteger val)

Compare the BigInteger with the specified BigInteger.

The remainder is used to calculate the remainder. Negate converts the operand to the opposite number. Compare details are as follows:

public int compareTo(BigInteger val)

Compare the BigInteger with the specified BigInteger. For the six Boolean comparison operators (<,=, >,>= ,! =, <=. The recommended statement for executing these comparisons is: (x. compareTo (y) <op> 0), where <op> is one of the six comparison operators.

Specified:

CompareTo in interface Comparable <BigInteger>

Parameters:

Val-compare the BigInteger with the BigInteger.

Implement precise floating point calculation in Java

Question:

What do we see if we compile and run the following program?

public   class   Test{             public   static   void   main(String   args[]){                     System.out.println(0.05+0.01);                     System.out.println(1.0-0.42);                     System.out.println(4.015*100);                     System.out.println(123.3/100);             }     };

You are not mistaken! The result is indeed

0.060000000000000005    0.5800000000000001    401.49999999999994    1.2329999999999999

The float and double types of simple floating point numbers in Java cannot be computed. Not only Java, but also in many other programming languages. In most cases, the calculation results are accurate, but you can try multiple times (you can do a loop) to try out errors similar to the above. Now we finally understand why we need BCD code.

This problem is quite serious. If you have 9.999999999999 yuan, your computer will not think you can buy 10 yuan of goods.

Some Programming Languages provide special currency types to handle this situation, but Java does not. Now let's take a look at how to solve this problem.

  • Rounding

Our first response was rounding. The round method in the Math class cannot be set to retain a few decimal places. We can only keep two places like this ):

public   double   round(double   value){             return   Math.round(value*100)/100.0;     }

Unfortunately, the code above does not work normally. If you pass 4.015 to this method, it will return 4.01 instead of 4.02, as we can see above

4.015*100=401.49999999999994

Therefore, if we want to perform precise rounding, we cannot use simple types for any operation.

Java. text. DecimalFormat cannot solve this problem either.

System.out.println(new   java.text.DecimalFormat("0.00").format(4.025));

The output is 4.02

  • BigDecimal

This principle is also mentioned in objective Java. float and double can only be used for scientific computing or engineering computing. In commercial computing, java. math. BigDecimal is used. BigDecimal has a total of four creation methods. We don't care about the two that can be created using BigInteger. There are two other methods:

BigDecimal(double   val)     // Translates   a   double   into   a   BigDecimal.     BigDecimal(String   val)     // Translates   the   String   repre   sentation   of   a   BigDecimal   into   a   BigDecimal.

The Brief description of the above API is quite clear, and it is usually easier to use the above one. We may use it if we don't want it. What's the problem? When a problem occurs, we can find a detailed description of the above method. It can be understood that if we need precise calculation, we must use String to create BigDecimal! The example in objective Java uses String to create BigDecimal, but this is not emphasized in the book. This may be a small mistake.

Solution

Now we can solve this problem. The principle is to use BigDecimal and must use String to create it.

But imagine, if we want to do an addition operation, we need to first convert two floating point numbers into strings, and then convert them into BigDecimal. Call the add method on one of them and input another as the parameter, then convert the result of the operation (BigDecimal) to a floating point number. Can you endure this cumbersome process? The following provides a tool class Arith to simplify operations. It provides the following static methods, including addition, subtraction, multiplication, division, and rounding:

public   static   double   add(double   v1,double   v2)   public   static   double   sub(double   v1,double   v2)   public   static   double   mul(double   v1,double   v2)   public   static   double   div(double   v1,double   v2)   public   static   double   div(double   v1,double   v2,int   scale)   public   static   double   round(double   v,int   scale)
Import java. math. BigDecimal;/*** Because Java's simple type cannot perform exact operations on floating point numbers, this tool class provides precise * real floating point operations, including addition, subtraction, multiplication, division, and rounding. */Public class Arith {// default Division calculation precision: private static final int DEF_DIV_SCALE = 10; // This class cannot be instantiated private Arith () {}/*** provides precise addition operations. * @ Param v1 add count * @ param v2 add count * @ return and */public static double add (double v1, double v2) {BigDecimal b1 = new BigDecimal (Double. toString (v1); BigDecimal b2 = new BigDecimal (Double. toString (v2); return b1.add (b2 ). doubleValue ();}/*** provides precise subtraction. * @ Param v1 subtrahend * @ param v2 subtrahend * @ return Difference Between Two Parameters */public static double sub (double v1, double v2) {BigDecimal b1 = new BigDecimal (Double. toString (v1); BigDecimal b2 = new BigDecimal (Double. toString (v2); return b1.subtract (b2 ). doubleValue ();}/*** provides exact multiplication. * @ Param v1 multiplier * @ param v2 multiplier * @ return product of two parameters */public static double mul (double v1, double v2) {BigDecimal b1 = new BigDecimal (Double. toString (v1); BigDecimal b2 = new BigDecimal (Double. toString (v2); return b1.multiply (b2 ). doubleValue ();}/*** provides (relatively) Precise Division operations. In case of Division, the Division is accurate to * 10 digits after the decimal point, and the subsequent digits are rounded down. * @ Param v1 divisor * @ param v2 divisor * @ return two parameter vendors */public static double div (double v1, double v2) {return div (v1, v2, DEF_DIV_SCALE);}/*** provides (relatively) accurate Division operations. In case of division, the scale parameter determines * the precision, and the number is rounded down. * @ Param v1 divisor * @ param v2 divisor * @ param scale indicates the number of digits after the decimal point. * @ Return operator of two parameters */public static double div (double v1, double v2, int scale) {if (scale <0) {throw new IllegalArgumentException ("The scale must be a positive integer or zero");} BigDecimal b1 = new BigDecimal (Double. toString (v1); BigDecimal b2 = new BigDecimal (Double. toString (v2); return b1.divide (b2, scale, BigDecimal. ROUND_HALF_UP ). doubleValue ();}/*** provides precise rounded decimal places. * @ Param v the number to be rounded off * @ param scale the number of digits to be retained after the decimal point * @ return the result after rounding */public static double round (double v, int scale) {if (scale <0) {throw new IllegalArgumentException ("The scale must be a positive integer or zero");} BigDecimal B = new BigDecimal (Double. toString (v); BigDecimal one = new BigDecimal ("1"); return B. divide (one, scale, BigDecimal. ROUND_HALF_UP ). doubleValue ();}};

I am the dividing line of tiantiao

 

 

Reference: http://jeelee.iteye.com/blog/652003


Java creates a class. Its function can be to generate a random positive integer of less than 100 and print it out (Note: Use Rando

Import java. util. Random;

// Generate a random positive integer within 100
Public class CustomRandom {

Public static int getRandomInt (){
Return (new Random (). nextInt (100 );
}

Public static void printRandomNumber (){
System. out. println (getRandomInt ());
}

Public static void main (String [] args ){
PrintRandomNumber ();
}
}

Public class CustomPayment {

Public static BigDecimal calculate (double payment, double price ){
BigDecimal bdPayment = new BigDecimal (payment );
BigDecimal bdPrice = new BigDecimal (price );
Return bdPayment. subtract (dbPrice );
}

Public static void main (String [] args ){
System. out. println (calculate (2.0d, 1.1d ));
}
}

Java sets for the precision of the bigdecimal type. 6 How do I write data in the hibernate ing file?

You can create a database table, create a data source using myeclipse, provide the project hibernate capabilities, and generate an object class using the data source, in this way, the entity classes and configuration files are automatically generated based on the database tables and table relationships, and even the associations are automatically generated. You only need to change the sequence to OK.

Related Article

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.