Last active
August 29, 2015 14:00
-
-
Save maarten00/aecfd07ae30af4328986 to your computer and use it in GitHub Desktop.
Pretty Price formatter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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