Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

numbers

Status
Not open for further replies.

Zas

Programmer
Oct 4, 2002
211
US
How can I round numbers down, and how can I round them up.
I.E. How can I get:
2 = 3 / 2;
# OR
1 = 3 / 2;
Thanks, Happieness is like peeing your pants.
Everyone can see it, but only you can feel the warmth.
 
To round down, you can use the int() function,
which will discard the fractional part of the
result:

print int(3 /2) #prints "1"

To round them up, add 0.5 after the division and
before you apply th int() function:

print int(3 / 2 + 0.5) #prints "2"

 
errr.. oh i see for rounding up, only it would be + 1, because 3.1 rounded all the way up is 4.

hrm.
$ttr = int( 3 / 2 );
# $trr is than 1? ok. thanks Happieness is like peeing your pants.
Everyone can see it, but only you can feel the warmth.
 
You can also use the ceil() and floor() functions in the POSIX module.

Example:
=========
use POSIX;

print floor(3/2) . "\n" . ceil(3/2) . "\n";
=========

This doesn't exactly round the number, but it does return the floor and ceiling.
 
The POSIX solution is better because the "int" solution will produce problems for divisions where there is no fraction. Suppose your division is 4/2. Both the round-down and round-up should be 2 whereas the "int" solution you've listed here will probably return 3 for the round-up.

 
add 0.5 and truncate is the just the world's fastest simple rounding, it's not always a round up. For instance:

1.2 + 0.5 = 1.7 truncated/rounded: 1
1.8 + 0.5 = 2.3 truncated/rounded: 2
1.5 + 0.5 = 2.0 truncated/rounded: 2

I don't know about any speed issues with the POSIX module, but the solutions sound simple enough a manual implementation might be best. I'm sure rounding down would be fastest just truncating. Rounding up might be best as truncating and adding one. ----------------------------------------------------------------------------------
...but I'm just a C man trying to see the light
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top