Reputation: 1473
I am trying to get exact calculated value (in my case it should be 66.66... not 66.0) but it prints 66.0
If I will get 66.66 then I can use Math.round(66.66) so that I will get 67
Below code after execution should return 66.66 but it returns 66.0
double d = (2*100)/3
Please suggest..
Regards
Upvotes: 0
Views: 134
Reputation: 14658
You are using all int values in your arithmetic operation so final result will always be int and when you put it into a double then it becomes 66.0. But since original result is int, so you loose precision.
You can use double d = (2.0*100.0)/3.0;
or have at least one value with decimal point, so that you can get expected decimal points.
Number after decimal point is commonly known as precision. So, the issue which you talked about is commonly known as floating-point imprecision, and in your case you can call it as double-point imprecision.
Rule of thumb:
Upvotes: 0
Reputation: 2417
As other answers suggested , you can provide at least one floating number. Or if you don't want to change the numbers, you can add cast to the numerator
double d= (double)(2*100)/3;
System.out.println(d);
prints
66.66666666666667
Upvotes: 1
Reputation: 2691
As Eran says it's your expression perform integer arithmetic you need to perform like
double d = (double) (2*100)/3;
if needs format the result.
Upvotes: 0
Reputation: 393771
(2*100)/3
performs integer multiplication and division, which results in an integer.
You need to force floating point calculation by changing one of the operands to an double (or float):
double d = (2.0*100)/3
Upvotes: 3