Formatting price as a comma

My database has values ​​like

256.23, 200.33, 89.33, 133.45,

I need to multiply these values ​​by a thousand and then format the result as a price (comma)

256.23 x 1000 = 256230 I want to show this as 256,230

200.33 x 1000 = 200330 I want this as 200,330

89.33 x 1000 = 89330 I want this as 89,330

I am currently using the formula

echo "Price is : $".$price*1000;

But how to format this, I have no idea.

+9
source share
6 answers

You are looking for the number_format function .

$price=123456;
echo number_format($price);
// output: 123,456

This function takes one, two or four parameters (not three):

, , ( "," ) .

, ( "." ) ( "," ) .

, , dec_point ( "." ) _sep ( "," ) .

+23
<?php

$number = 1234.56;

// english notation (default)
$english_format_number = number_format($number);
// 1,235

// French notation
$nombre_format_francais = number_format($number, 2, ',', ' ');
// 1 234,56

$number = 1234.5678;

// english notation without thousands separator
$english_format_number = number_format($number, 2, '.', '');
// 1234.57

?>
+3

number_format,

echo number_format(8333*1000, 3, ',', '.');
+2

$number = 1234.56;

Setlocale (LC_MONETARY, "en_US" );

echo money_format ( "% i", $number);

// " 1,234.56 "

0

The answers above do not include decimals or rounding; this may be useful for people who need to worry about decimals:

Examples: show without decimals, use spaces instead of commas and print with decimals and commas:

$price = 1000000.90;
var_dump(number_format(floor((float) $price), 0, ',', ' '));
var_dump(number_format($price, 2, '.', ','));

Output:

string(9) "1 000 000"
string(12) "1,000,000.90"
0
source

Here is a custom function for converting prices to the Indian price format using PHP 7+

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 formats, adds a zero in the beginning to maintain the 2 grouping.
        $expunit = str_split($restunits, 2);
        for($i=0; $i<sizeof($expunit); $i++) {
            // creates each of the 2 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.
}


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

All Articles