Asked  7 Months ago    Answers:  5   Viewed   37 times

How do you convert a number to a string showing dollars and cents?

123.45    => '$123.45'
123.456   => '$123.46'
123       => '$123.00'
.13       => '$0.13'
.1        => '$0.10'
0         => '$0.00'



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:

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');
Wednesday, March 31, 2021
answered 7 Months ago

assuming your cell is A1 ..

            'code' => PHPExcel_Style_NumberFormat::FORMAT_PERCENTAGE_00
Wednesday, March 31, 2021
answered 7 Months ago

See the locale module.

This does currency (and date) formatting.

>>> import locale
>>> locale.setlocale( locale.LC_ALL, '' )
'English_United States.1252'
>>> locale.currency( 188518982.18 )
>>> locale.currency( 188518982.18, grouping=True )
Tuesday, June 1, 2021
answered 5 Months ago

There is a string method called zfill:

>>> '12344'.zfill(10)

It will pad the left side of the string with zeros to make the string length N (10 in this case).

Tuesday, July 27, 2021
answered 3 Months ago

You can just do:

string.Format("{0}", yourDouble);

It will include only digits when necessary.

If you want other examples of formatting doubles to string check out this link.

EDIT: Based on your comment you want the , seperator so you could do:

string.Format("{0:0,0.########}", yourDouble);

Just put as many # for the max number of decimal places you want to show. It will only show the digits when necessary but up to the maximum digits based on how many # you include in the format. The # means only show a digit if necessary so if you give a number like 123 with no decimal, it will display as 1,234 but if you give it 1234.456, it will display as 1,234.456. If you go beyond the max digits you specified they will be rounded.

EDIT: To fix your double zero scenario just change it to:

string.Format("{0:#,0.########}", yourDouble);

That should work perfectly now :)

Tuesday, August 3, 2021
answered 3 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :