S Singh
S Singh

Reputation: 1473

java- issue in getting correct value with decimal

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

Answers (4)

hagrawal7777
hagrawal7777

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:

  1. If either is of type double, the other is converted to double for arithmetic operation and final result will be a double.
  2. Otherwise, if either is a float, the other is converted to float for arithmetic operation and final result will be a float.
  3. Otherwise, if either is of type long, the other is converted to long for arithmetic operation and final result will be a long.
  4. Otherwise, both operands are converted to int for arithmetic operation and final result will be a int.

Upvotes: 0

Amit.rk3
Amit.rk3

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

Shekhar Khairnar
Shekhar Khairnar

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

Eran
Eran

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

Related Questions