Skip to content

Instantly share code, notes, and snippets.

@santhoshtr
Created September 13, 2011 17:30
Show Gist options
  • Save santhoshtr/1214435 to your computer and use it in GitHub Desktop.
Save santhoshtr/1214435 to your computer and use it in GitHub Desktop.
Format a number using given format
<?php
function formatNumber($format, $string)
{
$numMatches = preg_match_all("/(#+)/", $format, $matches);
preg_match("/\d+/", $string, $numberpart);
preg_match("/\.\d*/", $string, $decimalpart);
$groupedNumber = (count($decimalpart)>0)?$decimalpart[0]:"";
$start = $end = strlen($numberpart[0]);
if($numMatches==0){
return $string;
}
while($start>0)
{
$match = $matches[0]{$numMatches-1};
$matchLen = strlen($match);
$start = $end - $matchLen;
$groupedNumber = substr($string ,$start, $end-$start).$groupedNumber ;
$end -= $matchLen;
if($numMatches > 1){
//use the last pattern for the rest of the number
$numMatches--;
}
if($start>0){
$groupedNumber = ",".$groupedNumber;
}
}
return $groupedNumber;
}
print formatNumber("##,##,###", "123456789")."\n";
print formatNumber("##,##,##", "123456789123456789")."\n";
print formatNumber("##,####", "123456789123456789")."\n";
print formatNumber("##,####", "123456789123456.789")."\n";
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment