DecimalFormat格式化输出带小数的数字类型


刚開始

double d = 333333333.333333333;
System.out.println(d);
输出结果为3.333333333333333E8

网上找到了DecimalFormat对象

double d = 333333333.333333333;
DecimalFormat decimalFormat = new DecimalFormat("#.#");
System.out.println(decimalFormat.format(d));
结果为333333333.3,发现假设要输出后面的小数,就须要把字符串改为"#.####",没添加一个#就添加一位小数

我认为这个非常麻烦,看了下帮助文档,发现有Max值。试了下输出

DecimalFormat decimalFormat = new DecimalFormat("#.#");
System.out.println("Integer:"+decimalFormat.getMaximumIntegerDigits()+"\nFraction:"+decimalFormat.getMaximumFractionDigits());
			

结果为

Integer:2147483647
Fraction:0

看来是我版本号默认的小数位数值。太少了,所以改动下值

double d = 333333333.333333333;
DecimalFormat decimalFormat = new DecimalFormat("#.#");
//decimalFormat.setMaximumIntegerDigits(100);//显示整数的最大字数,默认值足够大
decimalFormat.setMaximumFractionDigits(1000);//显示小时位的最大字数
System.out.println("Integer:"+decimalFormat.getMaximumIntegerDigits()+"\nFraction:"+decimalFormat.getMaximumFractionDigits());
System.out.println(decimalFormat.format(d));


输出结果为

Integer:2147483647
Fraction:1000

333333333.3333333

最终符合要求了












posted on 2017-07-01 08:12  blfbuaa  阅读(262)  评论(0编辑  收藏  举报