Php format price with commas

In my database I have values like

256.23, 200.33, 89.33, 133.45,

I have to multiply these values with thousand and then format the result as price[comma separated]

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

Currently I am using formula

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

But how to format this, I've no idea.

asked Jul 25, 2012 at 12:37

2

You are looking for the number_format function.

$price=123456;
echo number_format[$price];
// output: 123,456

This function accepts either one, two, or four parameters [not three]:

If only one parameter is given, number will be formatted without decimals, but with a comma [","] between every group of thousands.

If two parameters are given, number will be formatted with decimals decimals with a dot ["."] in front, and a comma [","] between every group of thousands.

If all four parameters are given, number will be formatted with decimals decimals, dec_point instead of a dot ["."] before the decimals and thousands_sep instead of a comma [","] between every group of thousands.

answered Jul 25, 2012 at 12:38

FluffehFluffeh

32.8k16 gold badges66 silver badges80 bronze badges


answered Jul 25, 2012 at 13:11

ObhasoObhaso

4311 gold badge4 silver badges14 bronze badges

0

Check number_format, here is an example

echo number_format[8333*1000, 3, ',', '.'];

answered Jul 25, 2012 at 12:41

FabioCostaFabioCosta

2,9494 gold badges27 silver badges49 bronze badges

1

The answers above do not account for decimals or rounding, this may be helpful to people who need to worry about decimals:

Examples: show no decimals use spaces instead of commas, and print with decimal 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"

answered Jun 20, 2018 at 16:42

Mike QMike Q

6,0384 gold badges50 silver badges57 bronze badges

1

$number = 1234.56;

setlocale[LC_MONETARY,"en_US"];

echo money_format["The price is %i", $number];

//output will be "The price is USD 1,234.56"

answered Apr 21, 2014 at 9:36

DJ MHADJ MHA

5983 silver badges18 bronze badges

Here is the custom function to convert price into 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's formats, adds a zero in the beginning to maintain the 2's grouping.
        $expunit = str_split[$restunits, 2];
        for[$i=0; $i

Chủ Đề