Chapter03 国际化(二) 数字格式

来源:互联网 发布:空气净化器有用吗 知乎 编辑:程序博客网 时间:2024/05/22 03:11

对于不同的国家,货币和数字表示方式不同,这就需要数据格式转化。

我们分为的三个步骤来解析:

1.得到Locale对象,即需要转化为哪个国家的

2.使用工厂模式获取格式化器对象

3.使用格式化器对象转化

测试代码如下图:

@Testpublic void test2() throws ParseException{//1.得到Locale对象Locale locale=new Locale(Locale.FRENCH.getLanguage(),Locale.FRANCE.getCountry());//2.使用工厂方法获取格式化器对象NumberFormat numberFormat=NumberFormat.getNumberInstance(locale);NumberFormat currencyFormat=NumberFormat.getCurrencyInstance(locale);NumberFormat fmt=NumberFormat.getPercentInstance();//3.使用格式化器来进行解析String s=numberFormat.format(1232.78);//将货币转化为法郎String money=currencyFormat.format(1222334);System.out.println(s);System.out.println(money);//将字符串解析为数字,可能会抛出异常Number num=currencyFormat.parse(money);System.out.println(num.doubleValue());//百分数转化String percent=fmt.format(0.4);System.out.println(percent);}
对于NumberFormat的各个方法:

@Testpublic void test2() throws ParseException{//1.得到Locale对象Locale locale=new Locale(Locale.FRENCH.getLanguage(),Locale.FRANCE.getCountry());//2.使用工厂方法获取格式化器对象NumberFormat numberFormat=NumberFormat.getNumberInstance(locale);NumberFormat currencyFormat=NumberFormat.getCurrencyInstance(locale);NumberFormat fmt=NumberFormat.getPercentInstance();//3.使用格式化器来进行解析String s=numberFormat.format(1232.78);//将货币转化为法郎String money=currencyFormat.format(1222334);System.out.println(s);System.out.println(money);//将字符串解析为数字,可能会抛出异常Number num=currencyFormat.parse(money);System.out.println(num.doubleValue());//百分数转化String percent=fmt.format(0.4);System.out.println(percent);//为法国人设置澳元格式currencyFormat.setCurrency(Currency.getInstance(Locale.CANADA));//打印出2 344 233 242,00 CADString doller=currencyFormat.format(2344233242L);System.out.println(doller);}


原创粉丝点击