DecimalFormat的疑惑(float与double)

 前几天做一个程序,要格式化的Float型数据最多5位小数,要求输出的格式为“有几位小数显示几位,不能用科学计数法表示”
用DecimalFormat格式化,格式化的模式为“0.#####”,
但对float a = 1234.22f,总是格式化不对,被莫名其妙的格式化为1234.21997
于是写了下面的一个小测试程序:
public static void main(String[] agrs)
 {
  DecimalFormat df = new DecimalFormat("0.#####");
  float a = 12345.22f;
  float b = 1234.22f;
  float c = 123.22f;
  float d = 0.123456789f;
 
  double e = 123456789.22; 
  System.out.println("Before Formation");
  System.out.println(a);
  System.out.println(b);
  System.out.println(c); 
  System.out.println(d);
 
  System.out.println(e);

 
  System.out.println("After Formation");
  System.out.println(df.format(a)); 
  System.out.println(df.format(b)); 
  System.out.println(df.format(c));
  System.out.println(df.format(d));
 
  System.out.println(df.format(e));
 
  df = new DecimalFormat("0.################################################################################");
  System.out.println("Format double type");
  System.out.println(df.format(e));
 }
输出的结果为:
 Before Formation
  12345.22
  1234.22
  123.22
  0.12345679
  1.2345678922E8
 After Formation
  12345.21973
  1234.21997
  123.22
  0.12346
  123456789.22
 Format double type
  123456789.22
 
关于这个测试结果的疑问及个人解释:
1。1234.22f ---> 1234.21997   123.22f ---> 123.22
Float类型的精度为8位  格式化串为"0.#####"
123.22f整数部分3位,加上“#####“5位,一共8位,在精度范围内,故被格式化为123.22
1234.22f整数部分4位,加上“#####“5位,一共9位,超出精度范围,故被格式化为1234.21997
2。double类型
 double e = 123456789.22 
 格式化串为"0.################################################################################", 一共80个“#”
却一直是正确的,是否对于double在此时不检查是否超出精度
结论:
建议在用浮点类型数据以double型为主,尽量少用float
1.double精度高于float
2.避免格式化时出现上面讨论的现象

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值