简体   繁体   中英

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

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

Try:

echo round($num, 2);

The second parameter rounds number decimal digits to round to.

More Info:

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

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM