Justine MARTIN
Justine MARTIN

Reputation: 29

Round a number at 0.5

I try to round a number at 0.5

This is my examples :

5.1 > 5
2.4 > 2.5
1 > 1
6.8 > 7
6.2 > 6.5

I try with :

<?php
round((4.4 * 2) / 2)
?>

But :

5.4 > 5
4.7 > 5

instead of

5.4 > 5.5
4.7 > 4.5

Any idea ?

Upvotes: 2

Views: 4000

Answers (3)

Andreas
Andreas

Reputation: 23968

Echo round(4.4 / 0.5)*.5;

You should think like this:
You want the number to be divided by the fraction you want. (0.5).
Then you round that number which means you remove the fraction and then multiply with the fraction you want again to get back to the number you had but rounded.

Just look at the calculation and let it sink in and you will understand it.

If you want to always round down, use floor instead of round.
If you want to round up, use ceil instead of round.

As an example

Echo round(12 / 5)*5;

Will round to closest 5.

Upvotes: 0

Stefan Dochow
Stefan Dochow

Reputation: 1454

Why not just double the value, round on a full number and then devide by 2:

$res = round($value*2) / 2

That should do the trick.

Upvotes: 6

matiit
matiit

Reputation: 8017

round(4.4*2)/2;

You are just mixing up the order.

You want to round up the number which is original number multiplied by 2 and after that round - you want to divide it by 2.

I hope that helps.

Upvotes: 2

Related Questions