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
热门推荐
10 诗词送行祝福语大全简短
11 新房开工吉日祝福语简短
12 50多岁生日简短祝福语
13 安徽疫情祝福语简短英语
14 农民朋友发财祝福语简短
15 对生活祝福语简短精辟
16 搬家词简短祝福语朋友
17 女神结婚快乐祝福语简短
18 文学短句祝福语大全简短