我们经常要将数字进行格式化,比如取2位小数,这是最常见的。Java 提供DecimalFormat类,帮你用最快的速度将数字格式化为你需要的样子。下面是一个例子:
importjava. text. DecimalFormat;
public class TestNumberFormat {
public static void main ( String[ ] args) {
doublepi= 3.1415927 ;
System. out. println ( newDecimalFormat ( "0" ) . format ( pi) ) ;
System. out. println ( newDecimalFormat ( "0.00" ) . format ( pi) ) ;
System. out. println ( new DecimalFormat ( "00.000" ) . format ( pi) ) ;
System. out. println ( newDecimalFormat ( "#" ) . format ( pi) ) ;
System. out. println ( new DecimalFormat ( "#.##%" ) . format ( pi) ) ;
longc= 299792458 ;
System. out. println ( newDecimalFormat ( "#.#####E0" ) . format ( c) ) ;
System. out. println ( newDecimalFormat ( "00.####E0" ) . format ( c) ) ;
System. out. println ( newDecimalFormat ( ",###" ) . format ( c) ) ;
System. out. println ( newDecimalFormat ( "光速大小为每秒,###米。" ) . format ( c) ) ;
}
}
DecimalFormat 类主要靠 # 和 0 两种占位符号来指定数字长度。0 表示如果位数不足则以 0 填充,# 表示只要有可能就把数字拉上这个位置。上面的例子包含了差不多所有的基本用法,如果你想了解更多,请参考 DecimalFormat 类的文档。