How is the NumberFormat used in Java?
The NumberFormat class in Java is used for formatting numbers, providing static and instance methods for formatting and parsing numbers.
- Retrieve NumberFormat instance using static methods.
- getInstance(): Returns a general number formatter for the current default language environment.
- getCurrencyInstance() returns a general currency formatter for the current default locale.
- getPercentInstance(): returns a general percentage formatter for the current default language environment.
- Example methods:
- setMaxIntegerDigits(int newValue): Set the maximum number of integer digits.
- setMinimumIntegerDigits(int newValue): Specify the minimum number of integer digits.
- Set maximum number of decimal places.
- setMinimumFractionDigits(int newValue): sets the minimum number of decimal places.
- setGroupingUsed(boolean newValue): enable/disable grouping (thousands separator).
- format(double/long/Number number): Convert a number into a formatted string.
- parse(String source): parse the string into a number.
Example code:
import java.text.NumberFormat;
public class NumberFormatExample {
public static void main(String[] args) {
double number = 12345.6789;
// 获取通用数值格式器
NumberFormat numberFormat = NumberFormat.getInstance();
String formattedNumber = numberFormat.format(number);
System.out.println("通用格式化:" + formattedNumber);
// 获取货币格式器
NumberFormat currencyFormat = NumberFormat.getCurrencyInstance();
String formattedCurrency = currencyFormat.format(number);
System.out.println("货币格式化:" + formattedCurrency);
// 获取百分比格式器
NumberFormat percentFormat = NumberFormat.getPercentInstance();
String formattedPercent = percentFormat.format(number);
System.out.println("百分比格式化:" + formattedPercent);
// 解析字符串为数字
String source = "12,345.6789";
try {
double parsedNumber = numberFormat.parse(source).doubleValue();
System.out.println("解析结果:" + parsedNumber);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output result:
通用格式化:12,345.679
货币格式化:¥12,345.68
百分比格式化:1,234,568%
解析结果:12345.679
The NumberFormat class makes it easy to format and parse numbers in order to meet various display requirements.