# Hey Guys I need some help with rounding...

• 12-07-2009, 08:07 AM
blueduiker
Hey Guys I need some help with rounding...
Hi guys,

So basically, for some reason my mind has gone blank in the middle of doing my project. For a part of this project I need to have the numbers if the tenths digit is 5 or greater round up. How would you recommend doing this using an if-statement?
• 12-07-2009, 08:28 AM
blueduiker
guys i need to get this done by 11 otherwise my parents r gonna whip me w/ a belt!

• 12-07-2009, 09:20 AM
CodesAway
I wouldn't use an if statement. I would use Math.round.
• 12-07-2009, 09:28 AM
blueduiker
oh yeah I should have check the math functions...

thanks!
• 12-07-2009, 04:37 PM
elektronika
Or you can also use something very simple like this :

Code:

```int a; float d = 0.121334; d = d + 0.5; a = (int)(d);```
then the a is the rounding of the d~~! (if d >= 0.5 it will become 1, else 0)

Kindest Regards,

Elektronika
• 12-07-2009, 05:35 PM
those parantessed around d isnt required tho, I think..
• 12-07-2009, 05:42 PM
elektronika
Yes,,you can just do not use it..
I just like to make things a bit fancy (it is just mystyle of programming),,

Kindest Regards,

Elektronika
• 12-07-2009, 10:06 PM
CodesAway
Quote:

Originally Posted by elektronika
Or you can also use something very simple like this :

Code:

```int a; float d = 0.121334; d = d + 0.5; a = (int)(d);```
then the a is the rounding of the d~~! (if d >= 0.5 it will become 1, else 0)

Your method only works for positive values. Instead of doing a cast to int, you should be taking the floor.

Code:

```int a; float d = -.99f; d = d + 0.5f; a = (int)(d); // a is 0, but should be 1```

The Math.round method is a convenience method for adding .5 and taking the floor - which rounds the value to the nearest integer. Below is the Java source code for Math.round.
Code:

```public static int round(float a) {         return (int)floor(a + 0.5f); }```
• 12-08-2009, 09:58 AM
elektronika
Thank you CodesAway..yes indeed mine is only for positive values..except you put another if..
so if positive value then +0.5, if negative value then -0.5..easy huh?

0.99 + 0.5 = 1.49 -> 1
-0.99 - 0.5 = -1.49 -> -1

But anyway the round method is there..so using it I think is better to use it :)

Kindest Regards,

Elektronika