Roundup of 5 in 5 cents

6

In a PHP system I'm developing, I need to update a column of the price table. The price field is in float format and the administrator informs the percentage of increase.

Example: Reports that it will have a 10% increase.

$valor_antigo = 4,25;

$novo_valor = round(($valor_antigo + ($valor_antigo / $percentual)),2);

So, the value after the increase will be 4.68. Setting to leave only two houses after the comma.

What I need now is to round these amounts down by five cents. If I use ceil or 'floor, I will have this rounding by only 1 in 1.

For example, the value of 4.68 above needs to be saved as 4.70. ' If the value were 5.22; would be 5,20. 7.46, would be 7.45.

How can I do this?

    
asked by Developer1903 27.02.2016 в 16:17

1 answer

8

You have to normalize to the point you want. If you want every 5 cents you divide the value by 0.05 by rounding it and then multiplying it by 0.05 (5 cents) again, so you go back to the original value without the unwanted fractional part.

round($value / 0.05, 0) * 0.05

See running on ideone .

Using float for monetary values is asking you to have problems.

    
27.02.2016 / 16:50