关于精度问题

      原价是18元,优惠17.99元,保存的最终价格是0.02元。看了一下代码:

  discount = (long) (Double.parseDouble(dis)*100);
  freight = (long) (Double.parseDouble(fre)*100);

      用这段代码做了测试就发现问题所在了。是精度问题,然后强制long转换后,把小数后面的内容给丢了。

	public static void main(String[] args) {
		//System.out.println((long) Math.round((Double.parseDouble("17.99")*100)));
		System.out.println((Double.parseDouble("17.99")*100));
		System.out.println((long) (Double.parseDouble("17.99")*100));

		System.out.println((Double.parseDouble("10.99")*100));
		System.out.println((long) (Double.parseDouble("10.99")*100));

		System.out.println((Double.parseDouble("8.99")*100));
		System.out.println((long) (Double.parseDouble("8.99")*100));
	}

 输出结果:

  

1798.9999999999998
1798
1099.0
1099
899.0
899

最简单的解决方案,在long强制转化前四舍五入,代码如下

System.out.println((long) Math.round((Double.parseDouble("17.99")*100)));

 更优化的写法当然是用bigDecimal,上面只是最偷懒的修改方式。

猜你喜欢

转载自5keit.iteye.com/blog/2331607