Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java BigDecimal to String

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;
}
like image 766
Taher Ali Avatar asked Sep 13 '26 13:09

Taher Ali


1 Answers

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.

like image 128
Seelenvirtuose Avatar answered Sep 15 '26 04:09

Seelenvirtuose



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!