Created
September 13, 2011 17:30
-
-
Save santhoshtr/1214435 to your computer and use it in GitHub Desktop.
Format a number using given format
This file contains 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 | |
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