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
终于符合要求了