Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java DecimalFormat losing precision while formatting double

When i execute the below code:

public class Test {
    public static void main(String args[]){
        DecimalFormat format = new DecimalFormat();
        Double value = new Double(-1350825904190559999913623552.00);

        StringBuffer buffer = new StringBuffer();
        FieldPosition position = new FieldPosition(0);
        format.format(new BigDecimal(value), buffer, position);
        System.out.println(buffer);
    }
}

This correctly prints -1,350,825,904,190,559,999,913,623,552. I have code which does go through a lot of doubles so I dont want the conversion from double to bigdecimal. I figured the processing time for BigDecimal is large. So i do format.format(value, buffer, position) And i see the precision is lost. The output I get is -1,350,825,904,190,560,000,000,000,000.

What am i doing wrong here? Is there a better way to deal with this and still retain the precision. I don't want to deal with BigDecimals here but just work with the decimals.

Any suggestions?

like image 566
Anusha Pachunuri Avatar asked Sep 02 '25 08:09

Anusha Pachunuri


1 Answers

double doesn't have infinite precision, and you can't gain more precision than a double has by converting a double to a BigDecimal (like you can't gain more precision with an int when you do double r = 1/3; which is 0.0 because it widens an int to a double). Instead, you could use a String. Something like

DecimalFormat format = new DecimalFormat();
String value = "-1350825904190559999913623552.00";
System.out.println(format.format(new BigDecimal(value)));
like image 93
Elliott Frisch Avatar answered Sep 04 '25 23:09

Elliott Frisch