DecimalFormat的疑惑
来源:互联网 发布:如何做网络推广 编辑:程序博客网 时间:2024/05/24 02:12
前几天做一个程序,要格式化的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>- DecimalFormat的疑惑
- DecimalFormat的疑惑
- DecimalFormat的疑惑
- DecimalFormat的疑惑(float与double)
- DecimalFormat的用法介绍
- DecimalFormat的用法介绍
- DecimalFormat的使用
- DecimalFormat的使用实例
- DecimalFormat的用法介绍
- DecimalFormat类的学习
- DecimalFormat的用法
- DecimalFormat的用法
- DecimalFormat的简单应用
- DecimalFormat类的用法
- DecimalFormat格式化数字的
- DecimalFormat的使用
- DecimalFormat的使用例子
- DecimalFormat类的使用
- TOMCAT笔记(一)之 目录、虚拟主机、SERVER.XML、TOO
- 用SQL获取月份的工作日
- 几个常用开源项目的地址荟萃(转)
- 功能不错的分页存储过程,可支持多表查询,任意排序
- [隆重介绍]Gemini:.NET project issue tracking...
- DecimalFormat的疑惑
- 您可能不知道的.Net2.0小技巧
- 中断19引导加载程序过程详解
- rs.getString VS rs.getDouble
- 新闻内容分页
- SpringFramework(1)
- 常见文件的http中content-type头的值(MIME类型)
- 弹出窗口,转向下一页
- JAVA MSN机器人主要代码开放