[英]Double multiplying with int issue
double temp = 64.1;
System.out.println("Result = " + (temp*1000));
The result would be: 结果将是:
Result = 64099.99999999999
But the actual result should be 64100
但是实际结果应该是64100
In case of Double data type 如果是Double数据类型
double a = ((temp * 1000) % (0.5 * 1000));
a=7.275957614183426E-12;
In case of casting it to float 如果将其浇铸成漂浮的
((((float) temp) * 1000) % (0.5 * 1000));
a=0.0;
Why this behaviour? 为什么这种行为?
Is a typical numeric problem with floating point numbers , when you multiple eg double * int. 当您使用倍数(例如double * int)时,是浮点数的典型数字问题 。
First option use Math.round: 第一选择使用Math.round:
Math.round((temp*1000))
Second option use BigDecimal class: 第二种选择使用BigDecimal类:
BigDecimal temp = BigDecimal.valueOf(64.1);
BigDecimal thousand = BigDecimal.valueOf(1000);
BigDecimal result = temp.multiply(thousand);
//example how to extract int or double value
int intResult = result.intValue();
double doubleResult = result.doubleValue();
System.out.println("Result = " + result);
Try this out 试试看
double temp = 64.1;
int x = 1000;
System.out.println("Answer :" + Math.round((temp*x)));
I think you can use ceil() method of JAVA. 我认为您可以使用JAVA的ceil()方法。
double temp = 64.1; 双温度= 64.1;
System.out.println("Result = " + Math.ceil(temp*1000)); System.out.println(“ Result =” + Math.ceil(temp * 1000));
I hope this helps. 我希望这有帮助。
The double in Java represents floating point number. Java中的double表示浮点数。 It has 64 bits value, which consist of: 它具有64位值,其中包括:
Source: https://en.wikipedia.org/wiki/Double-precision_floating-point_format 资料来源: https : //en.wikipedia.org/wiki/Double-precision_floating-point_format
Unlike fixed point numbers (byte, int, long), floating point number can't always consistently return exact same representation of a number. 与定点数(字节,整数,长整数)不同,浮点数不能始终一致地返回数字的完全相同的表示形式。 That's the reason why you get the result 64099.99999999999 instead of 64100. 这就是为什么得到结果64099.99999999999而不是64100的原因。
Use BigDecimal in Java in order to get better control of decimal places. 在Java中使用BigDecimal以便更好地控制小数位。
Source: https://docs.oracle.com/javase/8/docs/api/java/math/BigDecimal.html 资料来源: https : //docs.oracle.com/javase/8/docs/api/java/math/BigDecimal.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.