Java如何更改DecimalFormat模式?
要通过DecimalFormat格式化数字来更改模式使用,我们可以使用DecimalFormat.applyPattern()方法调用。在此示例中,我们使用三种不同的模式来格式化给定的输入数字。该模式确定格式化数字的外观。
package org.nhooo.example.text;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Locale;
public class FormatterPattern {
public static void main(String[] args) {
String[] patterns = {"###,###,###.##", "000000000.00", "$###,###.##"};
double before = 1234567.899;
//要获取特定语言环境的NumberFormat,
//包括默认语言环境,请调用NumberFormat的其中之一
//工厂方法,例如getNumberInstance()。然后投
//将其转换为DecimalFormat。
DecimalFormat format = (DecimalFormat) NumberFormat.getNumberInstance(Locale.UK);
for (String pattern : patterns) {
//将给定模式应用于此Format对象
format.applyPattern(pattern);
//获取格式化值
String after = format.format(before);
System.out.printf("Input: %s, Pattern: %s, Output: %s%n", before, pattern, after);
}
}
}程序的输出如下所示:
Input: 1234567.899, Pattern: ###,###,###.##, Output: 1,234,567.9 Input: 1234567.899, Pattern: 000000000.00, Output: 001234567.90 Input: 1234567.899, Pattern: $###,###.##, Output: $1,234,567.9