Java accurate calculation, with BigDecimal to deal with int, double, float and so on between the calculation __java

Source: Internet
Author: User
Tags mul

1, first look at the problem I encountered: Calculate 3 times 4.9 of the value, the normal answer should be 14.7, but if you use the following code to execute after the answer is:

Package com.acconsys.plugin.test;


public class Doubletest {public

	static void Main (string[] args) {
		int i1 = 3;
		Double D1 = 4.9;
		System.out.println (i1);
		System.out.println (d1);
		System.out.println (I1*D1);
	}


The results of the implementation are as follows:

3
4.9
14.700000000000001


Can see the above answer is not what we want, then if we can get the answer we want, one way is through the Code manual screenshot to get the answer to the decimal point after the unnecessary numbers, Another approach is to use Java to provide us with a built-in class java.math.BigDecimal to accurately compute.


So if the code above is modified to the following code, you can calculate exactly:

Package com.acconsys.plugin.test;

Import Java.math.BigDecimal;

public class DoubleTest2 {public

	static void Main (string[] args) {
		BigDecimal B1 = new BigDecimal (Integer.tostrin G (3));;
		BigDecimal b2 = new BigDecimal (double.tostring (4.9));
		System.out.println (B1);
		System.out.println (B2);
		System.out.println (b1.multiply (B2));
	}


The results of the implementation are as follows:

3
4.9
14.7


About BigDecimal do the following simple introduction

--------------------------------------------------------------------------------------------------------------- -----------

using BigDecimal for exact operations

First let's look at the following code example:

1 public class Test_1 {
2 public     static void Main (string[] args) {
3         System.out.println (0.06+0.01);
4         System.out.println (1.0-0.42);
5         System.out.println (4.015*100);
6         System.out.println (303.1/1000);
7     }
8     
9}

The results of the operation are as follows.

0.06999999999999999

0.5800000000000001

401.49999999999994

0.30310000000000004

You think you read it wrong, but it turns out to be. Where is the problem? The reason is that our computer is binary. Floating-point numbers do not have the means to accurately represent the binary. Our CPU represents floating point number consists of two parts: exponent and mantissa, such a method of expression will generally lose a certain degree of precision, some floating-point operations will produce a certain error. For example, the binary representation of 2.4 is not exactly 2.4. Instead the nearest binary representation is 2.3999999999999999. The value of a floating-point number is actually computed by a particular mathematical formula.

In fact, the Java float can only be used for scientific calculations or engineering calculations, in most commercial computing, the general use of Java.math.BigDecimal class for accurate calculation.

When using the BigDecimal class to compute, it is mainly divided into the following steps:

1, with float or double variable to build BigDecimal object.

2, by calling BigDecimal, subtraction, multiplication, in addition to the corresponding methods for arithmetic operations.

3, convert the BigDecimal object into Float,double,int and other types.

Generally, you can use the BigDecimal constructor or the static method's valueof () method to construct variables of the base type into BigDecimal objects.

1 BigDecimal b1 = new BigDecimal (double.tostring (0.48));
2 BigDecimal b2 = bigdecimal.valueof (0.48);

For commonly used addition, subtraction, multiplication, addition, the BigDecimal class provides the corresponding Member method.

1 public BigDecimal Add (BigDecimal value);                        Addition
2 public BigDecimal subtract (BigDecimal value);                   Subtraction 
3 public BigDecimal multiply (BigDecimal value);                   Multiplication
4 public BigDecimal divide (BigDecimal value);                     Division


After the corresponding calculation, we may need to convert the BigDecimal object to the corresponding basic data type variables, you can use Floatvalue (), Doublevalue () and other methods.

The following is a tool class that provides add, subtract, multiply, and divide operations.

 1 public class Arith {2/** 3 * Add method for exact addition calculation 4 * @param value1 summand 5 * @param value2 addends 6 * @return two parameters and 7/8 public static double Add (double value1,double value2) {9 BigDecimal B1 = new
BigDecimal (double.valueof (value1));
BigDecimal b2 = new BigDecimal (double.valueof (value2));
One return B1.add (B2). Doublevalue (); 12} 13 14/** 15 * Provides a sub method for exact subtraction @param value1 is @param value2 meiosis * @ret The difference between two parameters of a URN/public static double sub (double value1,double value2) {BigDecimal B1 = new Bigdeci
Mal (double.valueof (value1));
BigDecimal b2 = new BigDecimal (double.valueof (value2));
Return B1.subtract (B2). Doublevalue (); 24} 25 26/** 27 * Provides a mul method for accurate multiplication operations * @param value1 multiplier * @param value2 multiplier * @ret Two parameters of urn/* public static double Mul (double value1,double value2) {ADecimal B1 = new BigDecimal (double.valueof (value1));
BigDecimal b2 = new BigDecimal (double.valueof (value2));
B1.multiply (B2). Doublevalue (); 36} 37 38/** 39 * Provides precise division methods div * @param value1 dividend @param value2 divisor * @par AM scale the exact range @return two parameters of the business * @throws illegalaccessexception public static double div
 (double value1,double value2,int scale) throws illegalaccessexception{
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.