Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Converting long into currency

Tags:

I am having trouble converting a long (cents) into currency format.

My Code:

long doublePayment = 1099;  //Should equal $10.99
DecimalFormat dFormat = new DecimalFormat();
String formattedString = dFormat.format(doublePayment);
System.out.println(formattedString);

Output: 1,099

I also tried:

long doublePayment = 1099;
NumberFormat n = NumberFormat.getCurrencyInstance(Locale.US); 
String s = n.format(doublePayment);
System.out.println(s);

Since this is cents, the output should be 10.99 or $10.99.

Cant figure out what I am doing wrong. Thanks!!!

like image 668
mcd Avatar asked Sep 24 '12 07:09

mcd


People also ask

How do you format currencies in Java?

Java provides an automated way for formatting currencies depending on the locale. getCurrencyInstance() is a static method of the NumberFormat class that returns the currency format for the specified locale. Note: A Locale in Java represents a specific geographical, political, or cultural region.


2 Answers

In case You have long to start with, you still should use java.math.BigDecimal.

    long doublePayment = 1099;
    BigDecimal payment = new BigDecimal(doublePayment).movePointLeft(2);
    System.out.println("$" + payment); // produces: $10.99

Let it be once again said out loud: One should never use floating-point variables to store money/currency value.

like image 162
Lauri Avatar answered Sep 21 '22 07:09

Lauri


To convert cents to dollars you can use

long doublePayment = 1099;
NumberFormat n = NumberFormat.getCurrencyInstance(Locale.US); 
String s = n.format(doublePayment / 100.0);
System.out.println(s);

This will be accurate up to $70 trillion.

like image 27
Peter Lawrey Avatar answered Sep 21 '22 07:09

Peter Lawrey