NumberFormat数字格式化

1.NumberFormat表示数字的格式化类

比较全的学习链接:https://www.cnblogs.com/baiqiantao/p/6738842.html

1    public static Locale[] getAvailableLocales()              普通    返回所有语言环境的数组
2    public static final NumberFormat getInstance()            普通    返回当前默认语言环境的数字格式
3    public static NumberFormat getInstance(Locale inLocale)       普通    返回指定语言环境的数字格式
4    public static final NumberFormat getCurrencyInstance()        普通    返回当前缺省语言环境的通用格式,根据当前语言环境获取货币数值格式。
5    public static NumberFormat getCurrencyInstance(Locale inLocale) 普通    返回指定语言环境的数字格式    //Locale.CHINA  ¥3.4
            getPercentInstance()        方法获取百分比的数值格式  

  是NumberFormat的子类

2.DecimalFormat格式化数字

允许我们指定格式模式获取我们想要的格式化数值,数值的小数部分,默认显示3位小数

            Double  d=Double.parseDouble(num);
            java.text.NumberFormat percentFormat =java.text.NumberFormat.getPercentInstance(); 
            percentFormat.setMaximumFractionDigits(2); //最大小数位数
            percentFormat.setMaximumIntegerDigits(3);//最大整数位数
            percentFormat.setMinimumFractionDigits(2); //最小小数位数
            percentFormat.setMinimumIntegerDigits(1);//最小整数位数
            return percentFormat.format(d);//自动转换成百分比显示
0    表示一个数字,被格式化数值不够的位数会补0
#    表示一个数字,被格式化数值不够的位数会忽略
.    小数点分隔符的占位符
,    分组分隔符的占位符
-    缺省负数前缀
%    将数值乘以100并显示为百分数
\u2030    将数值乘以1000并显示为千分数
DecimalFormat format1 = new DecimalFormat("#\u2030");
System.out.println(format1.format(0.3345));//输出334‰
 
DecimalFormat format2 = new DecimalFormat("##.##");
System.out.println(format2.format(12.345));//输出12.35
 
DecimalFormat format3 = new DecimalFormat("0000.00");
System.out.println(format3.format(12.345));//输出0012.35
 
DecimalFormat format4 = new DecimalFormat("#.##%");
System.out.println(format4.format(12.345));//输出1234.5%

FormatDemo demo=new FormatDemo();
  demo.format("###,###.###", 111222.34567);
  demo.format("000,000.000", 11222.34567);
  demo.format("###,###.###$", 111222.34567);
  demo.format("000,000.000¥", 11222.34567);
  demo.format("##.###%", 0.345678);        // 使用百分数形式
  demo.format("00.###%", 0.0345678);        // 使用百分数形式
  demo.format("###.###\u2030", 0.345678);    // 使用千分数形式
 

3.ChoiceFormat格式化数字

ChoiceFormat允许将格式化运用到某个范围的数,通常与MessageFormat一同使用。ChoiceFormat在构造方法中接收一个format数组和一个limits数组,这两个数组的长度必须相等,例如

limits = {1,2,3,4,5,6,7}
formats = {"Sun","Mon","Tue","Wed","Thur","Fri","Sat"}

limits数组实际上是个区间,可开可闭,并且必须按升序排列,如果不按升序排列,格式化结果将会不正确,还可以使用\u221E(表示无穷大)。

ChoiceFormat的匹配公式

limit[j] <= X <limit[j+1]

其中X表示使用format方法传入的值,j表示limit数组中的索引。当且仅当上述公式成立时,X匹配j,如果不能匹配,则会根据X是太小还是太大,匹配limits数组的第一个索引或最后一个索引,然后使用匹配的limits数组中的索引,去formats数组中寻找相同索引的值。例子:

double[] limits = { 3, 4, 5, 6, 7, 8, 9 };
String[] formats = { "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日" };
ChoiceFormat format = new ChoiceFormat(limits, formats);
System.out.println(format.format(2.5));//将会输出"星期一"
/**3.6介于3和4之间,所以会匹配3,又由于3在limits数组中的索引是0,所以会在formats数组徐照索引0的值,即输出"星期一"
*/
System.out.println(format.format(3.6));

下面看一下ChoiceFormat类中的几个常用方法

1.nextDouble(double d)静态方法查找大于d的最小double值,用在limits数组中,从而使limits数组形成一个右开区间数组,例如

limits = {0,1,ChoiceFormat.nextDouble(1)}

2.nextDouble(double d, boolean positive)静态方法,如果positive参数为true,表示查找大于d的最小double值;如果positive参数为false,表示查找小于d的最大double值,这样就可以使limits形成一个左开区间数组。

3.previousDouble(double d)静态方法,查找小于d的最大double值
ChoiceFormat类的构造方法也允许我们传入一个模式字符串,format方法会根据这个模式字符串执行格式化操作。一个模式元素的格式如下:

扫描二维码关注公众号,回复: 5572477 查看本文章
doubleNum [占位符] formatStr

占位符可以使用#、< 、\u2264(<=)

ChoiceFormat cf = new ChoiceFormat("1#is 1 | 1<is more than 1");
System.out.println(cf.format(1));//输出"is 1"
System.out.println(cf.format(2));//输出"is more than 1"
System.out.println(cf.format(0));//输出"is 1"

由上面的例子可以看出,模式字符串中的每个模式元素之间使用"|"分割,"|"前后可以添加空格以美化代码,而且必须按照升序进行书写,否则会出现java.lang.IllegalArgumentException的运行时异常。
观看ChoiceFormat类的源码我们得知,实际上在内部,模式字符串还是被转换为limits和formats两个数组。在源码中

public ChoiceFormat(String newPattern)  {
     applyPattern(newPattern);
}
/** applyPattern(newPattern)方法的部分源码
*/
public void applyPattern(String newPattern) {
...
choiceLimits = new double[count];
System.arraycopy(newChoiceLimits, 0, choiceLimits, 0, count);
choiceFormats = new String[count];
System.arraycopy(newChoiceFormats, 0, choiceFormats, 0, count);
...
}

可以看出ChoiceFormat(String newPattern)调用了applyPattern(String newPattern)方法,在applyPattern方法中对newPattern字符串进行解析,然后将解析后的数据放置到ChoiceFormat类的两个私有属性double[] choiceLimitsString[] choiceFormats中,然后使用格式化方法即可。

3.MessageFormat

MessageFormat提供了以语言环境无关的生成连接消息的方式。
常用MessageFormat的静态方法format,该方法接收一个字符串的模式和一组对象(对象数组),按照模式形式将格式化的对象插入到模式中,然后返回字符串结果。
MessageFormat的格式模式元素(FormatElement)形式如下:
{ArgumentIndex}
{ArgumentIndex,FormatType}
{ArgumentIndex,FormatType,FormatStyle}
其中ArgumentIndex对象数组中的索引,从0开始,
FormatType包括number、date、 time、choice,
FormatStyle包括short、medium、long、full、integer、currency、percent、SubformatPattern(子模式),
在MessageFormat类的内部,FormatType和FormatStyle实际上是创建格式元素的Format示例
number对应了NumberFormat,其子格式对应了DecimalFormat
date和time对应了DateFormat,其资格是对应了SimpleDateFormat
choice对应了ChoiceFormat
敢说没有意思,来多举几个栗子:
你可以直接使用MessageFormat类中的静态方法format,像这样:

/**这是源码注释中的一个例子
* 在这个例子中静态方法format第一个参数是字符串类型的,
* 即模式字符串,第二个参数是个可变参数,实际上就是一个Object类型的数组。
* 在模式字符串中使用"{}"标识一个FormatElement。"{}"中的ArgumentIndex对应Object数组中响应索引处的值。
*/
int planet = 7;
String event = "a disturbance in the Force";
String result = MessageFormat.format("At {1,time} on {1,date}, there was {2} on planet {0,number,integer}.",
                  planet, new Date(), event);
System.out.println(result);
//输出:At 20:39:15 on 2015-12-11, there was a disturbance in the Force on planet 7.

你也可以使用MessageFormat的构造方法传入pattern string(模式字符串),然后调用普通的format方法,在这里就不举栗子了。
我们不仅被允许使用MessageFormat类中提供默认的FormatElement去format这些对象,还可以设置自己的Format对象format这些Object。

/**在这个例子中,MessageFormat和ChoiceFormat被结合使用
* MessageFormat类中有3个方法值的我们关注
* 1.setFormatByArgumentIndex(int argumentIndex, Format newFormat)//
* 2.setFormats(Format[] newFormats)
* 3.setFormat(int formatElementIndex, Format newFormat)
* 在这个例子当中,在MessageFormat的模式字符串的FormatElement(即{}中的内容)中
* 索引为0的地方将使用ChoiceFormat的格式去格式化。
* 如果在set的Format中仍具有FormatElement,则会递归调用MessageFormat的format方法。
*/
MessageFormat form = new MessageFormat("The disk \"{1}\" contains {0}.");
double[] filelimits = { 0, 1, 2 };
String[] filepart = { "no files", "one file", "{0,number} files" };
ChoiceFormat fileform = new ChoiceFormat(filelimits, filepart);
form.setFormatByArgumentIndex(0, fileform);
int fileCount = 1273;
String diskName = "MyDisk";
Object[] testArgs = { new Long(fileCount), diskName };
System.out.println(form.format(testArgs));
//输出:The disk "MyDisk" contains 1,273 files.

猜你喜欢

转载自www.cnblogs.com/luoyetl/p/10551625.html