2

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

4 Answers 4

4

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
Sign up to request clarification or add additional context in comments.

Comments

2

Try:

echo round($num, 2);

The second parameter rounds number decimal digits to round to.

More Info:

3 Comments

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.
I'm not sure why this is being up-voted, as it does not solve the question.
@Lucanos: True I assumed the same and waited for his response :)
0

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!

Comments

0
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.