Java数字的格式化

1、API层次结构:
java.text.Format
java.text.DateFormat
java.text.SimpleDateFormat
java.text.MessageFormat
java.text.NumberFormat
java.text.ChoiceFormat
java.text.DecimalFormat

主要用到粗体显示的类。

2、例子

import java.text.NumberFormat;
import java.text.DecimalFormat;
import java.util.Locale;

/**

  • Created by IntelliJ IDEA.
  • @author leizhimin 2010-3-22 19:12:33
    */
    public class TestNumFormat {

    public static void main(String[] args) { 
    
            DecimalFormat df1 = new DecimalFormat("###.00"); 
            System.out.println(df1.format(234234.234634)); 
            System.out.println(df1.format(34.234634)); 
    
            DecimalFormat df2 = new DecimalFormat("0.00E0000"); 
            System.out.println(df2.format(23423.34234234)); 
    
            DecimalFormat df3 = (DecimalFormat)NumberFormat.getInstance(Locale.CHINESE); 
            df3.applyPattern("####.000"); 
            System.out.println(df3.format(23423.34234234)); 
            df3.applyPattern("00.0000%"); 
            System.out.println(df3.format(0.5552445)); 
    
            NumberFormat nf1 = NumberFormat.getInstance(); 
            System.out.println(nf1.format(13423423.234234)); 
    
            NumberFormat nf2 = NumberFormat.getPercentInstance(); 
            System.out.println(nf2.format(0.55)); 
    
    } 

    }

输出结果:
234234.23
34.23
2.34E0004
23423.342
55.5244%
13,423,423.234
55%

Process finished with exit code 0

如果要将带一定格式的字符串数字转化为数字类型,则值需要调用格式对象的parse()方法即可。