I have below piece of code and my precision is getting lost while converting BigDecimal to String. Any help on this really appreciated.
Expected result : 95.10000000000000%
Actual Result : 95.09999999999999%
public static String getAsString(Object value)
{
if (value == null)
return null;
if (value.toString().length() == 0)
return null;
BigDecimal inputVal = new BigDecimal(value.toString());
if (inputVal == new BigDecimal(0))
return "";
NumberFormat numberFormat = NumberFormat.getPercentInstance(Locale.US);
numberFormat.setMinimumFractionDigits(14);
numberFormat.setMaximumFractionDigits(14);
if (numberFormat instanceof DecimalFormat) {
DecimalFormat df = (DecimalFormat) numberFormat;
df.setNegativePrefix("(");
df.setNegativeSuffix("%)");
}
String num = null;
num = numberFormat.format(new BigDecimal(95.1).divide(new BigDecimal(100)));
return num;
}
With this instance creation
new BigDecimal(95.1)
you are losing some precision. What you actually can do is to use the string constructor:
new BigDecimal("95.1")
Another way for your case is to use the factory methods:
BigDecimal.valueOf(95.1)
BigDecimal.valueOf(100)
Internally these use the string representation of those numbers to create a BigDecimal object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With