Function php - Working with currency values

2

Good evening, I'd like your help to solve a problem. Researching a little here I found a code that will help me work with a page for spending and income.

I would like to make this code not round the values. when I type 0.3 cents it returns 1. If I type 0.030 it returns 1 also and so on. I would like to be able to work with the correct decimal places because otherwise the final values will not hit my grades.

    function format_amount($n, $n_decimals) {
    return ((floor($n) == round($n, $n_decimals)) ? number_format($n).'.00' : number_format($n, $n_decimals));
}

Thank you in advance.

Source: link

    
asked by anonymous 12.12.2017 / 03:16

1 answer

1
  

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)
    
12.12.2017 / 05:06