Indian currency or rupee number format in PHP

Convert any amount to currency format is a tough task. money_format(), which is a custom function provided by PHP,  to change any number to currency formats. First you need to define the target locale and then specify the corresponding money format, which will do the trick for you.

<?php 

//We need to change the following number to Indian Currency (rupee) format
$number_to_convert = 12345678;

//The result will be "INR 1,23,45,678"
setlocale(LC_MONETARY, 'en_IN');
$formatted_currency = money_format('%i', $number_to_convert);
print($formatted_currency);


?>

Unfortunately the money_format() will not work properly in Windows machines. Windoes doesn't have strfmon capabilities. So while running this code in Windows, it will throw a Fatal error "Call to undefined function money_format() ". So we cant trust money_format() as it doesnt work on all platforms. Lets write a custom function for this purpose.

<?php 
function indianCurrencyNumberFormat($rupee) {
    $explore_remaining_units = "";
    if (strlen($rupee) > 3) {
        $last_three_digits = substr($rupee, strlen($rupee) - 3, strlen($rupee));
        $remaining_units = substr($rupee, 0, strlen($rupee) - 3); 
        $remaining_units = (strlen($remaining_units) % 2 == 1) ? "0".$remaining_units : $remaining_units; 
        $split_rupee = str_split($remaining_units, 2);
        for ($i = 0; $i < sizeof($split_rupee); $i++) {
          $explore_remaining_units .= (($i == 0) ? ( (int) $split_rupee[$i] . "," ) : ( $split_rupee[$i] . "," ));  
        }
        $formatted_rupee = $explore_remaining_units.$last_three_digits;
    } else {
        $formatted_rupee = $rupee;
    }
    return $formatted_rupee; 
}

//Calling the above function to convert a number to indian currency.
$number_to_convert = 12345678;
echo indianCurrencyNumberFormat($number_to_convert);
//The result will be "1,23,45,678"


// Happy Coding. 
?>

0 comments:

Post a Comment