Yes it sounds fairly elementary doesn’t it… yet I can’t find a PHP function to just do it?
If, like me, you store your currency values in your database as integers (don’t ask why, I just do) then you need to multiply by 100 on the way in and divide by 100 on the way out.
The obvious problem (or maybe not so obvious) is that when multiplying a number 100.1 is different to 100.10 and therefore the former needs to be converted to 100.10 for the resultant number to be correct.
The following function simply does that whilst checking for the occurence of a decimal place and concatenating .00 in that situation.
function convert_to_currency($num) {
if (strpos($num, '.') == false) {
$num = $num . '.00';
} else {
$num = sprintf("%01.2f", (float)$num);
}
return $num;
}
This should reliably format the number ready to be manipulated for either a database or to be directly output.
