tags:

views:

65

answers:

4

Hi, i try round function, but standart function don't good to me(all number must work in one function).

I have numbers: 0.7555 and 0.9298

And how round i this case: 
0.7555 - 0.75
0.9298 - 0.93

Thanks

+2  A: 

Try:

echo round($num, 2);

The second parameter rounds number decimal digits to round to.

More Info:

Sarfraz
Not sure whether the OP made a typo, but `round()` will turn 0.7555 into 0.76, not the 0.75 provided in the test cases above.
Lucanos
I'm not sure why this is being up-voted, as it does not solve the question.
Johannes Gorset
@Lucanos: True I assumed the same and waited for his response :)
Sarfraz
+3  A: 

Assuming that your test cases are exactly what you want...

function customRound( $inVal , $inDec ){
  return round( ( $inVal - pow( 10 , -1*($inDec+1) ) ) , $inDec );
}

Using this function you will get the following:

customRound( 0.7555 , 2 );
# Returns 0.75

customRound( 0.9298 , 2 );
# Returns 0.93

Update - If using PHP v5.3.0 or later

Found that using the round() function, with the correct mode, will do this automatically.

round( 0.7555 , 2 , PHP_ROUND_HALF_DOWN );
# returns 0.75

round( 0.9298 , 2 , PHP_ROUND_HALF_DOWN );
# returns 0.93
Lucanos
A: 
round(0.7555, 2)
# 0.76

round(0.7555, 2, PHP_ROUND_HALF_DOWN)
# 0.75

round(0.9298, 2, PHP_ROUND_HALF_DOWN)
# 0.93
Johannes Gorset
A: 

You could use:

echo number_format ($num, 2);

This specifically says round to two places after the decimal point. This works well when you are working with money and change. It allows 0.12 and 12.34. The function is also overloaded to allow you to change the delimiters; an example being languages that use ',' instead of '.' and it allows you to include a delimiter for separating by three digits for thousand, million, etc.

Using:

echo round ($num, 2);

will also give you 2 places after the decimal, but does not allow formatting the text.

ceil () and floor () allow you to round up and down respectively.

Good luck!

Robolulz