The round()
function is almost identical to the number_format()
function. THE
difference is that the second adds zeros to the right of the number if the
value of the second parameter is greater than the number of
the first parameter. If the second parameter is omitted or is equal to 0
, the number will be rounded to the next integer, if the decimal is equal to or greater than .5
, or to the previous one, if the decimal is less than .5
.
Ex.:
round(0.3,2); retorna 0.3
number_format(0.3,2); retorna 0.30
round(0.35); retorna 0
number_format(0.35); retorna 0
round(0.55); retorna 1
number_format(0.51); retorna 1
First suggestion is to remove from the format_amount($n, $n_decimals)
function the conditional within return
, which becomes unnecessary, leaving only return number_format($n, $n_decimals);
, like this:
function format_amount($n, $n_decimals) {
return number_format($n, $n_decimals);
}
The second suggestion is never send $n_decimals
to 0 or a number less than the number of decimal places of the number in $n
. If this is not observed, there is risk of rounding. See:
format_amount('0.3', '1') // ok! 1 casa decimal e 1. Irá retornar 0.3
format_amount('0.3', '2') // ok! 1 casa decimal e 2. Irá retornar 0.30
format_amount('0.35', '1') // errado! 2 casas decimais e 1. Irá retornar 0.4
format_amount('0.353', '2') // errado! 3 casas decimais e 2. Irá retornar 0.35
format_amount(0.353,0); // errado! 3 casas decimais e 0. Irá retornar 0 (igual a round)
format_amount(0.553,0); // errado! 3 casas decimais e 0. Irá retornar 1 (igual a round)
format_amount(0.557,2); // errado! 3 casas decimais e 2. Irá retornar 0.56 (igual a round)