Why 1000
(i.e., "thousand") becomes 10.00
(i.e., "ten" formatted with 2 decimal places), simply divide the value by 100 and use the function number_format
, with which you choose the number of decimal places to be displayed (in this case, 2
) and the character used as decimal separator (in this case, the point):
function formatar($valor) {
return number_format($valor / 100, 2, '.', '');
}
echo formatar(1000); // 10.00
echo formatar(10030); // 100.30
echo formatar(100000); // 1000.00
The fourth parameter is the thousands separator, but as it seems you do not want, just pass the empty string.
With this you can easily customize the amount of decimals:
function formatar($valor, $casas=2) {
return number_format($valor / (10 ** $casas), $casas, '.', '');
}
echo formatar(100000); // 1000.00
echo formatar(100000, 3); // 100.000
I find it much simpler than manipulating strings manually, picking pieces of it with substr
, making replace
, etc. It’s okay that number_format
should also manipulate strings internally, but still think better than doing everything in hand.
Another advantage of using a mathematical solution is that it also works for values less than 100. For example, formatar(1)
results in the string 0.01
- already using the solution of another answer (deleted), the result will be .1
(that is wrong because .1
corresponds to 0.10
).
It seems to me the same problem of this: Insert character in a specific position - Applied to your case:
substr_replace($valor, '.', -2, 0)
- in the case, the problem has nothing to do with decimal home formatting, its source data does not actually have decimal places, but is on another scale. Still, if it’s not a show, it’s enough$valor/100
instead of complicating. If it’s display issue, you’ll have to manipulate string of qq shape.– Bacco
To heitor’s response failure for values less than 10 (for example, if
1
, I believe that the result should be0.01
, but his solution results in.1
). I don’t know if you will have cases like this, but in any case there is the warning :-) (and also left an answer that works for these cases)– hkotsubo