user319854
user319854

Reputation: 4126

php, rounding number

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

Upvotes: 2

Views: 402

Answers (4)

Johannes Gorset
Johannes Gorset

Reputation: 8785

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

Upvotes: 0

Robolulz
Robolulz

Reputation: 178

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!

Upvotes: 0

Luke Stevenson
Luke Stevenson

Reputation: 10351

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

Upvotes: 4

Sarfraz
Sarfraz

Reputation: 382861

Try:

echo round($num, 2);

The second parameter rounds number decimal digits to round to.

More Info:

Upvotes: 2

Related Questions