介紹
-
我們經常要對數字進行格式化,比如取小數點后兩位小數,或者加個百分比符號等,Java提供了DecimalFormat這個類
-
0 和 # 的區別
"#"可以理解為在正常的數字顯示中,如果前綴與后綴出現不必要的多余的0,則將其忽略。
代碼示例
package com.tool.decimalFormat;
import java.text.DecimalFormat;
/**
*
*/
public class Demo1 {
public static void main(String args[]) {
double pi = 123.1512134567;
// 取整數部分
String s1 = new DecimalFormat("0").format(pi);
System.out.println("取整數:" + s1);//123
// 取小數點后1位,四舍五入
String s2 = new DecimalFormat("0.0").format(pi);
System.out.println(s2);//123.2
// 取小數點后3位,不足部分取0
String s3 = new DecimalFormat("0.000").format(pi);
System.out.println(s3);//123.150
// 百分比
String s4 = new DecimalFormat("0.0%").format(pi);
System.out.println(s4);// 12315.0%
// 科學計數法
String s5 = new DecimalFormat("0.00E0").format(pi);
System.out.println(s5);
double d = 1234567;
// 每三位以逗號分開
String s6 = new DecimalFormat(",000").format(d);
System.out.println(s6);
//小數點后3位,如果是0則不顯示
String s7 = new DecimalFormat("#.###").format(123.300);
System.out.println(s7);//123.3
}
}