Round method doesn't work

时间:2016-10-20 19:07:36

标签: java rounding

In my Java code, I tried to use Math.round() method. However, when the number is 204.6, method rounds it to 204. I couldn't solve this problem. Here is my code;

//all[i] value of the index zero is 186.
//and it prints 204 not 205.
double updatedPassed = all[i].getPassed()+((all[i].getPassed()*10)/100);
System.out.println(Math.round(updatedPassed));

4 个答案:

答案 0 :(得分:1)

Add a D to 100 to indicate that the division must be done with a floating value. In this way, you will get a floating result. Otherwise, it uses an integer value as result.
And as arithmetically, you get 204.XXX as result, it gives 204 as integer result.

//all[i] value of the index zero is 186.
//and it prints 204 not 205.
double updatedPassed = all[i].getPassed()+((all[i].getPassed()*10)/100D);
System.out.println(Math.round(updatedPassed));

答案 1 :(得分:0)

The code that multiplies all[i] by 10 and dividing by 100 will try and cast it to int. Try doing this:

double updatedPassed = all[i].getPassed()+(((double)all[i].getPassed()*10)/100);
System.out.println(Math.round(updatedPassed));

Hope this helps

答案 2 :(得分:0)

Extracted OP's answer from previous version of question:

I solved the problem with this changes:

double updatedPassed = (double)all[i].getPassed()+((double)(all[i].getPassed()*10)/100);

答案 3 :(得分:-1)

If your all[i] array is an array of integers, you'll run into this problem. The array needs to be of type double as integer division results in an integer.

Not sure if its the main issue as you didn't mention what type the array was.

相关问题