Skip to content
Advertisement

PHP number_format(): rounding numbers and then formatting as currency

I am trying to create an ecommerce store and our prices need to fluctuate with the exchange rate for different countries so I’m dealing with a lot of decimal places.

What I want to do is round the original price to the nearest full number (as in they can keep the change). But then I want to format that as a currency with two decimal places.

<?php
$number = 12345.6789;
echo $number;  // outputs '12345.6789'
$number = number_format($number,0);
echo $number;  // outputs '12,346'
$number = number_format($number,2);
echo $number;  // outputs '12.00'
?>

After formatting to no decimal places it starts reading the ‘,’ as the decimal separator instead of the thousands separator and formats that for two decimal places.

It also gives the following error:

A non well formed numeric value encountered in C:wamp64wwwLifting365test.php on line 6

How can I achieve what I am looking for?

Advertisement

Answer

As specified in the documentation, number_format returns a string value, you can’t reuse it as a number. Use the function round() to round your number, if you want to round it to the direct upper integer use ceil() instead.

number_format(round(12345.6789), 2);
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement