Saturday, July 9, 2016

Currency Formatter convert number to currency format

Here is example of How we can convert a Number in to Currency Format


Function to Convert Number to Currency
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function format_currency($number, $decimal_places=2, $decimal_symbol=".", $thousand_seperator=",", $currency_symbol="", $currency_symbol_position='before'){
if(!is_numeric($number)){
return $number;
}else{
$formatted_number = number_format($number, $decimal_places, $decimal_symbol, $thousand_seperator);
if($currency_symbol!=""){
if($currency_symbol_position=='after'){
$formatted_number = $formatted_number." ".$currency_symbol;
}else{
$formatted_number = $currency_symbol." ".$formatted_number;
}
}
return $formatted_number;
}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
USE
$number = 12450;
$formatted = format_currency($number );
echo $formatted ;

OUTPUT

12,450.00

As simple As that 

Another Function for Currenct format

function convertcash($num, $currency){ 
    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++){ 
if($expunit[$i]==0){

$explrestunits .= $expunit[$i].","; // creates each of the 2's group and adds a comma to the end 
}else{
                 $explrestunits .= (int)$expunit[$i].","; // creates each of the 2's group and adds a comma to the end 
            }
}    

            $thecash = $explrestunits.$lastthree; 
    } else { 
           $thecash = $convertnum; 
    } 
    
    return $currency.$thecash; // writes the final format where $currency is the currency symbol. 



USE

$formatted = convertcash(12450,'R');


echo $formatted ;

OUTPUT

R12,450

Thanks
Cheers

No comments:

Post a Comment