/*
* DecimalFormat 类主要靠 # 和 0 两种占位符号来指定数字长度 * 0 表示如果位数不足则以 0 填充 * # 表示只要有可能就把数字拉上这个位置 * */ public static void main(String[] args){ double pi=123.5678;//取所有整数部分 124
System.out.println(new DecimalFormat("#").format(pi)); //强制保留两位小数 123.57 System.out.println(new DecimalFormat("#.00").format(pi));pi=123.5;
//取所有整数部分 124 System.out.println(new DecimalFormat("#").format(pi)); //强制保留两位小数 123.50 System.out.println(new DecimalFormat("#.00").format(pi)); //强制保留两整数、两位小数 123.50 System.out.println(new DecimalFormat("00.00").format(pi)); //强制保留四整数、三位小数 0123.500 System.out.println(new DecimalFormat("0000.000").format(pi)); pi=0.9881; //以百分比方式计数,并取两位小数 98.81% System.out.println(new DecimalFormat("#.##%").format(pi));//注意一点
pi=0.98;
System.out.println(new DecimalFormat("#.00").format(pi));
// 猜猜结果是什么? .98
//api中文帮助文档关于”#”的翻译是错误的,原文为“zero shows as absent”译为“如果为0,则不显示”。
//“#”可以理解为在正常的数字显示中,如果前缀与后缀出现不必要的多余的0,则将其忽略。 }