Reputation: 21
double temp = 64.1;
System.out.println("Result = " + (temp*1000));
The result would be:
Result = 64099.99999999999
But the actual result should be 64100
In case of Double data type
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?
Upvotes: 1
Views: 3724
Reputation: 3990
Try this out
double temp = 64.1;
int x = 1000;
System.out.println("Answer :" + Math.round((temp*x)));
Upvotes: -1
Reputation: 121
The double in Java represents floating point number. It has 64 bits value, which consist of:
Source: 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.
Use BigDecimal in Java in order to get better control of decimal places.
Source: https://docs.oracle.com/javase/8/docs/api/java/math/BigDecimal.html
Upvotes: 0
Reputation: 1740
Is a typical numeric problem with floating point numbers, when you multiple e.g. double * int.
First option use Math.round:
Math.round((temp*1000))
Second option use BigDecimal class:
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);
Upvotes: 4
Reputation: 89
I think you can use ceil() method of JAVA.
double temp = 64.1;
System.out.println("Result = " + Math.ceil(temp*1000));
I hope this helps.
Upvotes: 0