3

I am using PHP number_format to express prices of products, using decimal point, thousands separators, etc. For example:

$price = 20.456;
print "$" . number_format($price, 2, ".", ",");

outputs $20.46.

However, I would like that, if the price is integer, for example $price = 20.00, to output $20. Is there some other function or rule to achieve this, avoiding decimal points if not necessary?

1
  • I choose billyonecan solution as it is quite elegant. I thought that the function itself may have a parameter for "respecting" integers, but that not being the case, it will suffice with the if-else comparison, which in ternary form is quite elegant. Commented Jun 28, 2016 at 10:11

6 Answers 6

9

Just do a loose comparison of $price cast as integer against $price, if they match (ie. it's a whole number), you can format to 0 decimal places:

number_format($price, ((int) $price == $price ? 0 : 2), '.', ',');
Sign up to request clarification or add additional context in comments.

Comments

3

You can use ternary operator fot that:

    $price = 20.456;
    print "$" . ($price == intval($price) ? number_format($price, 0, "", ",") : number_format($price, 2, "", ","));

Comments

3

Try $price = 20.456 +0 ;

$price + 0 does the trick.

echo  125.00 + 0; // 125
echo '125.00' + 0; // 125
echo 966.70 + 0; // 966.7

Internally, this is equivalent to casting to float with (float)$price or floatval( $price) but I find it simpler.

4 Comments

but that's not the desired result, trailing zeroes should only be removed if price is a whole number
@billyonecan you can try echo 1000000 + 0; // 1000000
echo 966.70 + 0; // 966.7 - desired result would be 966.70
Yes True. we have to write a function before we perform +0 to price, Thanks for advice, do you have any solution for this case.?
2

A little helper function my_format to determine if the number is an integer and then return the corresponding string.

function my_format($number)
{
    if (fmod($number, 1) == 0) {
        return sprintf("$%d\n", $number);
    } else {
        return sprintf("$%.2f\n", $number);
    }
}

$price = 20.456;

echo my_format($price);
echo my_format(20);

Will output

$20.46 $20

Comments

2

A little solution that works for any number

$price = "20.5498";
$dec = fmod($price, 1);
if($dec > 0)
    print "$" . number_format($price, 2, ".", ",");
else
    print "$" . floor($price);;

Comments

0

You can use floor() function

$price = 20.456;
echo '$'.floor($price); // output $20

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.