How do you convert a number to a string showing dollars and cents?
eg: 123.45 => '$123.45' 123.456 => '$123.46' 123 => '$123.00' .13 => '$0.13' .1 => '$0.10' 0 => '$0.00'
Advertisement
Answer
PHP also has money_format().
Here’s an example:
echo money_format('$%i', 3.4); // echos '$3.40'
This function actually has tons of options, go to the documentation I linked to to see them.
Note: money_format is undefined in Windows.
UPDATE: Via the PHP manual: https://www.php.net/manual/en/function.money-format.php
WARNING: This function [money_format] has been DEPRECATED as of PHP 7.4.0. Relying on this function is highly discouraged.
Instead, look into NumberFormatter::formatCurrency.
$number = "123.45"; $formatter = new NumberFormatter('en_US', NumberFormatter::CURRENCY); return $formatter->formatCurrency($number, 'USD');