Math.round and Math.ceil not working

I am trying to combine users, but I can show that my double is rounded to int. Basically, when I enter 4.4999, it doesn't round to 5.

Any ideas?

+4
source share
6 answers

Math.ceil() returns the limit value. It cannot change the value of the variable that it takes as an argument, because Java passes arguments by value. Therefore you need to do

 hours = Math.ceil(hours); 
+7
source

The actual solution is to use double inside the ceil method.

Math.ceil(7 * 50 / 100) will return 3.0 , although the actual value obtained as a result of 7*50/100 Math.ceil(7 * 50 / 100) is 3.5 . This is because, since everything is int , the result of 350/100 itself will be 3 .

If, however, if you give Math.ceil(7 * 50 / 100D) , the result will be 4.0 .

So, 4.999 in your question should be double , and not the result of an integer operation like 4999/1000 .

Just make sure that everything you give inside ceil is double , not int .

+6
source

Both functions return rounded (or ceiling) values, but do not change the variable passed as a parameter.

Use for example. hours = Math.ceil(hours); .

+3
source

You do not assign the result of Math.ceil(hours) back to hours , so it will never be rounded.

+2
source

Math.ciel returns a Double . Something like this should work (inside your hours > 0 block):

 cost += Math.ceil(hours) * hourlyRate; 
+1
source
 int a = 15 int b = 2; int x = (int) Math.ceil( a / b ); int y = (int) Math.ceil( (double) a / (double) b ); 

results

x: 7

y: 8

0
source

All Articles