Last active
November 3, 2015 23:26
-
-
Save JaggedJax/179a80b05c7f4a72e937 to your computer and use it in GitHub Desktop.
Format number or string as a float
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
<?php | |
/** | |
* Take a number or numerical string and format as float | |
* Supports US and UK formats. Designed for money but will work with other formats as well. | |
* @param mixed $amount | |
* @param int $decimal_places | |
* @param int $round_mode | |
* @return float | |
*/ | |
function money_float($amount, $decimal_places=2, $round_mode=PHP_ROUND_HALF_UP){ | |
if(empty($amount)){ | |
$amount = 0; | |
} | |
else if(is_object($amount)){ | |
$amount = (string)$amount; | |
} | |
if(is_string($amount)){ | |
$amount = trim($amount, "\$£€¥ \t\n\r\0\x0B"); | |
// Strip thousands separator | |
$comma = 0+strrpos($amount, ','); | |
$period = 0+strrpos($amount, '.'); | |
$len = strlen($amount); | |
// Strip thousands separator | |
if($period || $comma){ | |
if($comma && ($period > $comma || (!$period && ($len - $comma -1) % 3 == 0))){ | |
$amount = str_replace(',','',$amount); | |
} | |
else if($period && ($comma > $period || (!$comma && ($len - $period -1) % 3 == 0))){ | |
$amount = str_replace('.','',$amount); | |
} | |
} | |
$amount = floatval($amount); | |
} | |
return round(number_format($amount, $decimal_places+1, '.', ''), $decimal_places); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment