Previous I have written an article about formating interger into number of decimal places in Java. The main reason to store money value in integer in to prevent loss in precision. For example the actual value for 12.33 in float could be 12.3333333333…; while 1233 in integer is always 1233.
Today I will be showing you the same code but in PHP language. I know you can do the same thing with PHP’s number_format(), but you will need to cast the integer into float first before past the money value into the number_format() function. Therefore there are possibles of lose in precision.
Here is the code:
function format_money($money, $comma = true) { $stack = array(); $stackIndex = 0; $neg = $money < 0; if ($neg) $money = -$money; $prec = 2; while ($prec > 0) { $mod = $money % 10; $money = (int) ($money / 10); $stack[$stackIndex++] = ''.$mod; $prec--; } $stack[$stackIndex++] = '.'; $firstZero = true; $commaCnt = 0; while ($firstZero || $money > 0) { $mod = $money % 10; $money = (int) ($money / 10); $stack[$stackIndex++] = $mod; $firstZero = false; $commaCnt ++; if ($comma && $commaCnt == 3) { $commaCnt = 0; if ($money > 0) $stack[$stackIndex++] = ','; } } if ($neg) $stack[$stackIndex++] = '-'; $out = ''; while (--$stackIndex >= 0) { $out.= $stack[$stackIndex]; } return $out; }
Examples of input and output:
1000 --> 10.00 100000 --> 1,000.00 -1000 --> -10.00 -100000 --> -1,000.00
Leave a Reply