Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding Down to nearest whole number - am I cheating or is this more than adequate?

Tags:

java

Essentially, if the number generated is 2.3 then if I subtract .5 it will then be 1.8 but the rounding function will make it 2, which is what I want. Or if the answer is 2.99999 and I subtract .5, the answer is 2.49999 which should round down to 2 which is what I want. My question is if the answer is 2 even and I subtract .5, the answer is now 1.5, so will it still round up to 2.

temp1_1= Math.round(temp2_2/(360/temp_value)-.5);

this is my line of code for this.

like image 618
Kevin M Avatar asked Feb 19 '12 21:02

Kevin M


2 Answers

There is already a function to do that. It's called floor:

double d = Math.floor(2.9999) //result: 2.0
like image 192
Petar Ivanov Avatar answered Oct 24 '22 00:10

Petar Ivanov


Even simpler and potential faster

double d = 2.99999999;
long l = (long) d; // truncate to a whole number.

This will round towards 0. Math.floor() rounds towards negative infinity. Math.round(x - 0.5) also rounds towards negative infinity.

like image 35
Peter Lawrey Avatar answered Oct 24 '22 01:10

Peter Lawrey