Common objects in Java--bigdecimal

Source: Internet
Author: User

When we are in the process of development, double or float for the subtraction operation, there will be a case of loss of precision

In the following example, we can see the accuracy of the

Demo

public class Bigdecimaldemo {

public static void Main (string[] args) {

System.out.println (0.09 + 0.01);

System.out.println (1.0-0.32);

SYSTEM.OUT.PRINTLN (1.015 * 100);

System.out.println (1.301/100);

System.out.println (1.0-0.12);

}

This time, for the above situation, we introduce the object

BigDecimal class:

immutable, arbitrary-precision signed decimal numbers can be used to solve data loss problems.

Public BigInteger Add (BigInteger val): plus

Public BigInteger Subtract (BigInteger val): minus

Public BigInteger Multiply (BigInteger val): Multiply

Public BigInteger Divide (BigInteger val): except

Public biginteger[] Divideandremainder (BigInteger val): returns an array of quotient and remainder

Demo

public class Bigintegerdemo {

public static void Main (string[] args) {

BigInteger bi1 = new BigInteger ("100");

BigInteger Bi2 = new BigInteger ("50");

Public BigInteger Add (BigInteger val): plus

System.out.println ("Add:" + bi1.add (BI2));

Public BigInteger Subtract (BigInteger val): plus

System.out.println ("Subtract:" + bi1.subtract (BI2));

Public BigInteger Multiply (BigInteger val): plus

System.out.println ("Multiply:" + bi1.multiply (BI2));

Public BigInteger Divide (BigInteger val): plus

System.out.println ("Divide:" + bi1.divide (BI2));

Public biginteger[] Divideandremainder (BigInteger val): returns an array of quotient and remainder

biginteger[] bis = bi1.divideandremainder (BI2);

System.out.println (" quotient:" + bis[0]);

System.out.println (" remainder:" + bis[1]);

}

}

perfectly solves the problem of float type and double loss accuracy.

Common objects in Java--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.