Friday, May 30, 2008

Number to currency format conversion - Indian Rupees - in PHP

The following code can be used to convert the number format into indian currency format (Indian rupees, INR) using PHP.

<?php
ob_start();
//Currency format conversion - Indian Rupee
$n = "1000000";
$len = strlen($n); //lenght of the no
$num = substr($n,$len-3,3); //get the last 3 digits
$n = $n/1000; //omit the last 3 digits already stored in $num
while($n > 0) //loop the process - further get digits 2 by 2
{
$len = strlen($n);
$num = substr($n,$len-2,2).",".$num;
$n = round($n/100);
}
echo "Rs.".$num;
?>

4 comments:

Unknown said...

Very good indeed.
Does it work for 1000 Cr?
e.g 1400,00,00,000.00 is shown as Rs.14,00,00,+7,.00

Beski said...
This comment has been removed by the author.
Beski said...

it works.

Sathish said...

You have so many options but money_format http://php.net/manual/en/function.money-format.php can do the trick for you

Example

$amount = '100000';
setlocale(LC_MONETARY, 'en_IN');
$amount = money_format('%!i', $amount);
echo $amount;
Output

1,00,000.00
Note

The function money_format() is only defined if the system has strfmon capabilities. For example, Windows does not, so money_format() is undefined in Windows.

Edit 1

Pure PHP Implementation .... Works on any system:

$amount = '10000034000';
$amount = moneyFormatIndia( $amount );
echo $amount;

function moneyFormatIndia($num){
$explrestunits = "" ;
if(strlen($num)>3){
$lastthree = substr($num, strlen($num)-3, strlen($num));
$restunits = substr($num, 0, strlen($num)-3); // extracts the last three digits
$restunits = (strlen($restunits)%2 == 1)?"0".$restunits:$restunits; // explodes the remaining digits in 2's formats, adds a zero in the beginning to maintain the 2's grouping.
$expunit = str_split($restunits, 2);
for($i=0; $i<sizeof($expunit); $i++){
// creates each of the 2's group and adds a comma to the end
if($i==0)
{
$explrestunits .= (int)$expunit[$i].","; // if is first value , convert into integer
}else{
$explrestunits .= $expunit[$i].",";
}
}
$thecash = $explrestunits.$lastthree;
} else {
$thecash = $num;
}
return $thecash; // writes the final format where $currency is the currency symbol.
}