Domanda

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?

È stato utile?

Soluzione

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.

Altri suggerimenti

A double can indeed hold a number of that size. Unfortunately, it cannot hold one of that precision.

Range is the highest and lowest values that can be represented with a type, precision is the number of digits that can be stored.

The bottom line is that doubles have a range of about 10+/-308 but only about 15 decimal digits of precision. The Wikipedia page has some useful information about this as well.

As a fix, you should look into the Java BigDecimal type since it has arbitrary precision.

use the following code, checked at netbeas IDE and works fine

 NumberFormat currencyFormatter1 = NumberFormat.getCurrencyInstance(Locale.US);
        BigDecimal data= new BigDecimal("12385748375889879879894375893475984.03");
        System.out.println(currencyFormatter1.format(data));
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top