Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Currency Number format

Is there a way to format a decimal as following:

100   -> "100"   100.1 -> "100.10" 

If it is a round number, omit the decimal part. Otherwise format with two decimal places.

like image 936
DD. Avatar asked Mar 04 '10 12:03

DD.


People also ask

What is the currency number format?

United States (U.S.) currency is formatted with a decimal point (.) as a separator between the dollars and cents. Some countries use a comma (,) instead of a decimal to indicate that separation.

What is %d and %s in Java?

%s refers to a string data type, %f refers to a float data type, and %d refers to a double data type.

How do you format currencies in Java?

The NumberFormat class provides methods to format the currency according to the locale. The getCurrencyInstance() method of the NumberFormat class returns the instance of the NumberFormat class. The syntax of the getCurrencyInstance() method is given below: public static NumberFormat getCurrencyInstance(Locale locale)

What is number format in Java?

NumberFormat is the abstract base class for all number formats. This class provides the interface for formatting and parsing numbers. NumberFormat also provides methods for determining which locales have number formats, and what their names are. NumberFormat helps you to format and parse numbers for any locale.


1 Answers

I'd recommend using the java.text package:

double money = 100.1; NumberFormat formatter = NumberFormat.getCurrencyInstance(); String moneyString = formatter.format(money); System.out.println(moneyString); 

This has the added benefit of being locale specific.

But, if you must, truncate the String you get back if it's a whole dollar:

if (moneyString.endsWith(".00")) {     int centsIndex = moneyString.lastIndexOf(".00");     if (centsIndex != -1) {         moneyString = moneyString.substring(1, centsIndex);     } } 
like image 69
duffymo Avatar answered Oct 11 '22 12:10

duffymo