PHP: Converting dollars to cents
$input[] = "$12.33";
$input[] = "14.92";
$input[] = "$13";
$input[] = "17";
$input[] = "14.00001";
$input[] = "$64.99";
foreach($input as $number)
{
$dollars = str_replace('$', '', $number);
echo number_format((float)$dollars*100., 0, '.', '');
}
Gives:
1233
1492
1300
1700
1400
6499
Watch out for corner cases like "$0.125". I don't know how you would like to handle those.
Ah, I found out why. When you cast (int)
on ($dollars*100)
it drops a decimal. I'm not sure WHY, but remove the int cast and it's fixed.
Consider using the BC Math extension, which does arbitrary-precision math. In particular, bcmul()
:
<?php
$input = '$64.99';
$dollars = str_replace('$', '', $input);
$cents = bcmul($dollars, 100);
echo $cents;
?>
Output:
6499