Skip to content

Instantly share code, notes, and snippets.

@maarten00
Last active August 29, 2015 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maarten00/aecfd07ae30af4328986 to your computer and use it in GitHub Desktop.
Save maarten00/aecfd07ae30af4328986 to your computer and use it in GitHub Desktop.
Pretty Price formatter
/**
* Helper function to format price
* Replaces dots with commas, replaces trailing zeroes with ,-
* If there is only 1 trailing zero, adds another
* Adds ,- for rounded prices
* @param $price
* @return mixed|string
*/
public static function prettyPrice($price)
{
//Replace the dot in the price with a comma.
$price = str_replace('.', ',', $price);
//If the price has two trailing zeroes, remove them.
$price = str_replace(',00', ',-', $price);
//If there is only one tracing zero after the comma, add another one
if(preg_match('/\d{2},\d{1}(?!\d{1})/', $price))
{
$price = $price . '0';
}
//If the price has no trailing zeroes, also add a dot with a comma
//We know it has no trailing zeroes if none of the above methods added a comma
if(! preg_match('~\,~', $price))
{
$price = $price . ',-';
}
return $price;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment