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.
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.
%s refers to a string data type, %f refers to a float data type, and %d refers to a double data type.
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)
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.
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); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With