Questions about BigDecimal multiply() method in Java

88 Views Asked by At

I've been trying to avoid precision loss in case of using BigDecimal multiply() method in Java.

Please check an example code below.

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;

public class HelloWorld{

 public static void main(String []args){
 
     double result = 0;
     NumberFormat formatter = new DecimalFormat("0.####################");
     formatter.setGroupingUsed(true);
 
     //10000000000
     //17911250000
     String strRt = formatter.format(10000000000.0);
     String strIrt = formatter.format(17911250000.0);
 
     System.out.println(strRt);
     System.out.println(strIrt);
 
     result = new BigDecimal(strRt).multiply(new BigDecimal(strIrt)).doubleValue();
 
    System.out.println(formatter.format(result));
 }

}

An expected result :

10000000000
17911250000
179112500000000000000

Result in console:

10000000000
17911250000
179112499999999980000

Is there any other way to get a precise result?

1

There are 1 best solutions below

1
RoToRa On

The whole point of BigDecimal is to avoid the lack of precision of double (and all other primitive number types). You however are using doubles to read (but also create) the BigDecimals thus reintroducing the lack of precision.

DecimalFormat directly supports BigDecimal, so there is no need to read the doubleValue. Also it's best to avoid using doubles to create the input values.

 NumberFormat formatter = new DecimalFormat("0.####################");
 formatter.setGroupingUsed(true);

 String strRt = "10000000000";
 String strIrt = "17911250000";

 System.out.println(strRt);
 System.out.println(strIrt);

 BigDecimal result = new BigDecimal(strRt).multiply(new BigDecimal(strIrt));

 System.out.println(formatter.format(result));