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?
The whole point of
BigDecimalis to avoid the lack of precision ofdouble(and all other primitive number types). You however are usingdoubles to read (but also create) theBigDecimals thus reintroducing the lack of precision.DecimalFormatdirectly supportsBigDecimal, so there is no need to read thedoubleValue. Also it's best to avoid usingdoubles to create the input values.