DecimalFormat的疑惑

来源:互联网 发布:如何做网络推广 编辑:程序博客网 时间:2024/05/24 02:12
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 160x600, 创建于 08-4-23MSDN */google_ad_slot = "4367022601";google_ad_width = 160;google_ad_height = 600;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>

前几天做一个程序,要格式化的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.22Float类型的精度为8位  格式化串为"0.#####"123.22f整数部分3位,加上“#####“5位,一共8位,在精度范围内,故被格式化为123.221234.22f整数部分4位,加上“#####“5位,一共9位,超出精度范围,故被格式化为1234.219972。double类型 double e = 123456789.22   格式化串为"0.################################################################################", 一共80个“#”却一直是正确的,是否对于double在此时不检查是否超出精度结论:建议在用浮点类型数据以double型为主,尽量少用float1.double精度高于float2.避免格式化时出现上面讨论的现象

<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 160x600, 创建于 08-4-23MSDN */google_ad_slot = "4367022601";google_ad_width = 160;google_ad_height = 600;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
原创粉丝点击