Hi I’m trying to run a calculation but I can’t seem to put it all on one line, I have to split the result into two seperate lines to achieve the desired result (which seems a bit long winded).
Can anyone explain where I’m going wrong?
both x and y are doubles.
Example 1: (incorrect)
y=0.68
x= (Math.round(y* 10))/10;
result x=0
Example 2: (correct)
y=0.68
x= Math.round(y* 10);
x = x/10;
result x=0.7
thanks for your time.
Math.roundreturns variable of typelong(see: Javadoc), which means that the division by10is performed on alongvariable resulting in anotherlongvariable – that’s why you lose the precision.To make it calculate on it as on
doubleand returndouble– you have to cast the result ofMath.roundlike this: