Nabeel Arshad
Nabeel Arshad

Reputation: 45

Number format in PHP

I want to display price in my front page. But the format of the number required is,

if I am using the following code

echo  number_format ($price,2,'.',',');

But through this the result is displayed in this manner.
Entered price: 10000 Display: 10,000.00

Please help me to solve this problem

Upvotes: 0

Views: 2680

Answers (4)

barryhunter
barryhunter

Reputation: 21081

Personally I would do

echo number_format($price,floor($price)==$price?0:2,'.',',');

displaying a price as 10,000.1 just looks odd to me.

But if you really must

$bits = explode('.',$price);
echo number_format($price,strlen($bits[1]),'.',',');

(edit) In reply to the comment, it works for me...

<?php
$a=array(10000.00,10000.10,10000.01);

foreach ($a as $price)
{
    $bits = explode('.',$price);
    echo $price.' - '.number_format($price,strlen($bits[1]),'.',',')."\n";
}
?>

$ php t.php
10000 - 10,000
10000.1 - 10,000.1
10000.01 - 10,000.01

Upvotes: 0

DaveyBoy
DaveyBoy

Reputation: 2924

Surely, from a clarity and consistency point of view, having 2 digits after the decimal point makes more sense especially when showing prices.

@barryhunter made a valid point and the following doesn't work.

echo rtrim(number_format($price,2,'.',','),'0.');

However, this does:

trim(trim(number_format($price,2,'.',','),'0'),'.');

Look:

<?php
$a=array('10000.00','10000.10','10000.01');

foreach ($a as $price)
{
    echo $price.' - '.rtrim(rtrim(number_format($price,2,'.',','),'0'),'.')."\n";
}
?>

$> php -f t.php
10000.00 - 10,000
10000.10 - 10,000.1
10000.01 - 10,000.01

Upvotes: 1

Ruben Nagoga
Ruben Nagoga

Reputation: 2218

You have set number of decimial points to 2 so that is why you have 10,000.00. Try to user in this way:

echo  number_format ($price,1,'.',',');

And also it is better to use money_format if you are working with money values.

Upvotes: 1

filype
filype

Reputation: 8410

There's a function in PHP called money_format().

Have a look at it on http://php.net/manual/en/function.money-format.php

Upvotes: 3

Related Questions