NumberFormat.getCurrencyInstance() turning everything to zero?

I've been working on this for hours and can't find a solution...

When I use this code:

 NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(Locale.US);
 System.out.println(currencyFormatter.format(12385748375889879879894375893475984.03));

It gives me the output: $12,385,748,375,889,900,000,000,000,000,000,000.00

What's the problem?? I'm giving it a double value which should be able to contain a number much much larger than what I'm supplying, but it's giving me all these useless zeros... Does anyone know why and what I can do to fix it?

Jon Skeet
people
quotationmark

The problem isn't in the size of the double you're using, but the precision. A double can only store 15-16 digits of precision, even though it can hold numbers much bigger than 1016.

If you want exact decimal representations - and particularly if you're using it for currency values - you should use BigDecimal. Sample code:

import java.text.*;
import java.math.*;
import java.util.*;

public class Test {
    public static void main(String[] args) {
        NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(Locale.US);
        BigDecimal value = new BigDecimal("12385748375889879879894375893475984.03");
        System.out.println(currencyFormatter.format(value));
    }
}

Output:

$12,385,748,375,889,879,879,894,375,893,475,984.03

For the record the double literal 12385748375889879879894375893475984.03 has an exact value of 12,385,748,375,889,879,000,357,561,111,150,592.

people

See more on this question at Stackoverflow