import java.text.NumberFormat;
There are three static methods in the NumberFormat class:
-
getCurrencyInstance() to format as $99,999.99
-
getPercentInstance() to format as 99%
-
getNumberInstance() to format as 99,999,999
There are three methods in NumberFormat object
-
format(anyNumberType)
-
setMinimumFactionDigits(int)
-
setMaximumFractionDigits(int)
Example 1: The currency format
double price = 11.575;
NumberFormat currency = NumberFormat.getCurrencyIstance();
String priceString = currency.format(price); // returns $11.58
Example 2: The percent format
double majority = .505;
NumberFormat percent = NumberFormat.getPercentInstance();
String majoriySring = percent.getformat(majority); // return 50%
Example 3: The number format with one decimal place
doulbe miles = 15342.351;
NumberFormat number = NumberFormat.getNumberInstance();
number.setMaimumFractionDigits(1);
String milesString = number.format(miles); // returns 15,354.3