Java中的浮点乘法 [英] Floating point multiplication in java

查看:397
本文介绍了Java中的浮点乘法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
如何将数字四舍五入到n个小数位Java

在Java中将两个数字相乘时会发生以下情况:

double a = 9.495 * 100;

预期结果:

a = 949.5;

但是获得的结果是:

a = 949.4999999999999

当我尝试将9.495的数字四舍五入到小数点后两位时,结果是9.49而不是9.50

有什么想法可以解决这个问题吗?

解决方案

如果要进行精确的浮点计算,请不要使用floatdouble类型,而应使用BigDecimal类. /p>

Possible Duplicate:
How to round a number to n decimal places in Java

When multiplying two numbers in java happens this:

double a = 9.495 * 100;

Expected result:

a = 949.5;

But the obtained result is:

a = 949.4999999999999

When I try to round number 9.495 in two decimal places the result is 9.49 instead of 9.50

Any ideas how to solve this problem?

解决方案

If you want accurate floating point computations, do not use the float or double types, but rather make use of the BigDecimal class.

这篇关于Java中的浮点乘法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆