看一道被不少人转载的文章: 我截取片段如下: if(amount > 99999999999999.99 || amount < -99999999999999.99)
throw new IllegalArgumentException("参数值超出允许范围 (-99999999999999.99 ~ 99999999999999.99)!"); boolean negative = false;
if(amount < 0) {
negative = true;
amount = amount * (-1);
} long temp = Math.round(amount * 100);
int numFen = (int)(temp % 10); // 分
temp = temp / 10;
int numJiao = (int)(temp % 10); //角
temp = temp / 10;
//temp 目前是金额的整数部分
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/liguohuaty/archive/2009/07/06/4326572.aspx
当amount = 99999999999999.99 时候 采用Math.round(amount * 100) 只能得到9999999999999998
99 9999 9999 9999.99 变成了
9999 9999 9999 9998也就是说在转换过程中丢失了精度 继续下面的测试:
System.out.println(Math.round(99999999999999.99));//100000000000000
System.out.println(Math.round(99999999999999.99*100));//9999999999999998
System.out.println((long)99999999999999.99*100);//9999999999999900即使我用 strictfp 关键字申明 也无法得到高精度的计算?? 还是理解有误精确取得该数据还有几种方法? 现在的我只能通过转换成char数组再以分析.的位置来判断整数与小数部分.请大家帮忙.谢谢!^_^
throw new IllegalArgumentException("参数值超出允许范围 (-99999999999999.99 ~ 99999999999999.99)!"); boolean negative = false;
if(amount < 0) {
negative = true;
amount = amount * (-1);
} long temp = Math.round(amount * 100);
int numFen = (int)(temp % 10); // 分
temp = temp / 10;
int numJiao = (int)(temp % 10); //角
temp = temp / 10;
//temp 目前是金额的整数部分
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/liguohuaty/archive/2009/07/06/4326572.aspx
当amount = 99999999999999.99 时候 采用Math.round(amount * 100) 只能得到9999999999999998
99 9999 9999 9999.99 变成了
9999 9999 9999 9998也就是说在转换过程中丢失了精度 继续下面的测试:
System.out.println(Math.round(99999999999999.99));//100000000000000
System.out.println(Math.round(99999999999999.99*100));//9999999999999998
System.out.println((long)99999999999999.99*100);//9999999999999900即使我用 strictfp 关键字申明 也无法得到高精度的计算?? 还是理解有误精确取得该数据还有几种方法? 现在的我只能通过转换成char数组再以分析.的位置来判断整数与小数部分.请大家帮忙.谢谢!^_^
的缘故是想给double赋值99999999999999.99就会丢失精度。
double d2 = 99999999999999.99;
System.out.println("right:"+d2);//right:9.999999999999998E13
可以这样做:
BigDecimal big1 = new BigDecimal("99999999999999.99");
BigDecimal big2 = new BigDecimal(100.0);
System.out.println(big1);//99999999999999.99
System.out.println("right:"+big1.multiply(big2));//right:9999999999999999.00
if(amount > 99999999999999.99 || amount < -99999999999999.99)
throw new IllegalArgumentException("参数值超出允许范围 (-99999999999999.99 ~ 99999999999999.99)!");
amount不允许超过99999999999999.99
比如
amount=99999999999999.99;那么输出amount为9.999999999999998E13
amount=99999999999999.989;那么输出amount为9.999999999999998E13
amount=99999999999999.98;那么输出amount为9.999999999999998E13
amount=99999999999999.97;那么输出amount为9.999999999999997E13
注意amount的取值不能超过99999999999999.99