PHP 8.4.24 Released!

Voting

: max(two, eight)?
(Example: nine)

The Note You're Voting On

swapnet
18 years ago
Consider formatting currency for some South Asian countries that use ##,##,###.## money format.
The following code generates something like Rs. 4,54,234.00 and so on.

<?php
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++){
                $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.".00"; // writes the final format where $currency is the currency symbol.
}
?>

now call the function as  convertcash($row['price'], 'Rs '); // that's the price from the database I called using an Indian Rupees prefix where the price has to be a plain number format, say something like 454234.

<< Back to user notes page

To Top