Skip to content

Instantly share code, notes, and snippets.

@JaggedJax
Last active November 3, 2015 23:26
Show Gist options
  • Save JaggedJax/179a80b05c7f4a72e937 to your computer and use it in GitHub Desktop.
Save JaggedJax/179a80b05c7f4a72e937 to your computer and use it in GitHub Desktop.
Format number or string as a float
<?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