Skip to content

Instantly share code, notes, and snippets.

@colynb
Last active May 22, 2023 05:09
Show Gist options
  • Save colynb/fde7f6c0fdae9170a8f1dcfd65935f85 to your computer and use it in GitHub Desktop.
Save colynb/fde7f6c0fdae9170a8f1dcfd65935f85 to your computer and use it in GitHub Desktop.
PHP - convert any dollar/cents amount into just cents
<?php
function to_pennies($value)
{
return intval(
strval(floatval(
preg_replace("/[^0-9.]/", "", $value)
) * 100)
);
}
echo to_pennies("1"); // 100
echo to_pennies("12"); // 1200
echo to_pennies("123"); // 12300
echo to_pennies("123.45"); // 12345
echo to_pennies("$123.45"); // 12345
echo to_pennies("$12,345.67"); // 1234567
echo to_pennies("$123,456.78"); // 12345678
echo to_pennies("$1,234,567.89"); // 123456789
@mforcer
Copy link

mforcer commented Jul 28, 2020

Thanks for sharing this. PHP Storm recommended converting it to this:

function toPennies($value): int
{
    return (int) (string) ((float) preg_replace("/[^0-9.]/", "", $value) * 100);
}

"To reduce cognitive load, up to 6x faster in PHP 5.x"

@colynb
Copy link
Author

colynb commented Jul 28, 2020

Thanks for sharing this. PHP Storm recommended converting it to this:

function toPennies($value): int
{
    return (int) (string) ((float) preg_replace("/[^0-9.]/", "", $value) * 100);
}

"To reduce cognitive load, up to 6x faster in PHP 5.x"

Nice! Didn't know anyone was using this. Thanks for the tip!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment