首页 > 技术文章 > Java SE基础部分——常用类库之NumberFormat(数字格式化)

newcode 2016-05-24 15:43 原文

数字格式化常用方法:DecimalFormat和NuberFormat。

 1 //2016060524     数字格式化学习     
 2 //数字格式化   两种方法  一种直接使用NumberFormat,另一种DecimalFormat。
 3 import java.text.NumberFormat;
 4 
 5 public class NumberFormatDemo {
 6 
 7     public static void main(String[] args) {
 8         NumberFormat nf=null;
 9         nf=NumberFormat.getInstance();
10         System.out.println(nf.format(10000));
11     }
12 
13 }

 

 

------------------------------DecimalFormat方法------------------------------------

 1 //2016060524     数字格式化学习     
 2 //数字格式化   两种方法  一种直接使用NumberFormat,另一种DecimalFormat。
 3 package Org;
 4 
 5 import java.text.DecimalFormat;
 6 
 7 class FormatDemo {
 8     public void format1(String pattern, double value) {
 9         DecimalFormat df = null;
10         df = new DecimalFormat(pattern);
11         String str = df.format(value);
12         System.out.println("使用" + pattern + "格式化数字" + value + ":" + str);
13     }
14 }
15 
16 public class DecimalFormatDemo {
17     public static void main(String args[]) {
18         FormatDemo demo = new FormatDemo();
19         demo.format1("###,###.###", 111222.34567);
20         demo.format1("000,000.000", 11222.34567);
21         demo.format1("###,###.###¥", 111222.34567);
22         demo.format1("000,000.000¥", 11222.34567);
23         demo.format1("##.###%", 0.345678);
24         demo.format1("00.###%", 0.0345678);
25         demo.format1("###.###\u2030", 0.345678);
26     }
27 }

 

DecimalFormat方法,运行结果:

1 使用###,###.###格式化数字111222.34567:111,222.346
2 使用000,000.000格式化数字11222.34567:011,222.346
3 使用###,###.###¥格式化数字111222.34567:111,222.3464 使用000,000.000¥格式化数字11222.34567:011,222.3465 使用##.###%格式化数字0.345678:34.568%
6 使用00.###%格式化数字0.0345678:03.457%
7 使用###.###‰格式化数字0.345678:345.678‰

 

推荐阅读