Monday, June 7, 2010

Round the float

There are 3 types of rounding a float to integer is applicable in any language. we programmers will come across such situation in every project. the three types are,

  1. round to next bigger integer, with not considering the decimal value.
  2. round to the next smaller integer, with not considering the decimal value.
  3. round the float according to the value of decimal value, the real round of float number.
The rounding methods depend on which scenario we need the round function.

Follows the examples of php rounding methods.
for the case 1, rounding to the next big integer, we use ceil() function
Example : 
$rounded_value = ceil($floor_value);
if rounded the following values, the results are like shown
2 = ceil(1.3)
2 = ceil(1.5)
2 = ceil(1.7)

for the case 2, round to the next small integer, we could use floor()
Example:
$rounded_value = floor($floor_value);
if rounded the following values, the results are like shown
1 = floor(1.3)
1 = floor(1.5)
1 = floor(1.7)

for the case 3, round as per the decimal value, we could use round()
Example:
$rounded_value = round($floor_value);
if rounded the following values, the results are like shown
1 = round(1.3)
2 = round(1.5)
2 = round(1.7)

Wicked Cool PHP: Real-World Scripts That Solve Difficult Problems   

No comments:

Post a Comment