Kai Liu Kai Liu - 3 years ago 184
Java Question

Java Convert Long to Currency, Why is there 1 cent difference and What's the safe way to convert such long to currency?

Following is my code to convert long (cents) to dollar, however, there is 1 cent difference.

My expected answer is:

$123,456,789,123,456.47
, but the output is
$123,456,789,123,456.48


public static void main(String[] args) {
long l = 12345678912345647L;
double d = l / 100.00;
NumberFormat formatter = NumberFormat.getCurrencyInstance();
System.out.println(formatter.format(d));
}

Answer Source

To be completely honest, I'm not entirely sure why but this seems to work?

public static void main(String[] args) {
        BigDecimal l = new BigDecimal("12345678912345647");
        BigDecimal d = l.divide(new BigDecimal("100.00"));
        NumberFormat formatter = NumberFormat.getCurrencyInstance();

        System.out.println(formatter.format(d));
    }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download