PHP Numbers
Formatting Numbers
Problem
You have a number and you want to print it with thousands and decimal separators. Forexample, you want to display the number of people who have viewed a page, or the
percentage of people who have voted for an option in a poll.
Solution
If you always need specific characters as decimal point and thousands separators, usenumber_format():
$number = 1234.56;
// $formatted1 is "1,235" - 1234.56 gets rounded up and , is
// the thousands separator");
$formatted1 = number_format($number);
// Second argument specifies number of decimal places to use.
// $formatted2 is 1,234.56
$formatted2 = number_format($number, 2);
// Third argument specifies decimal point character
// Fourth argument specifies thousands separator
// $formatted3 is 1.234,56
$formatted3 = number_format($number, 2, ",", ".");
If you need to generate appropriate formats for a particular locale, use Number Formatter:
$number = '1234.56';
// $formatted1 is 1,234.56
$usa = new NumberFormatter("en-US", NumberFormatter::DEFAULT_STYLE);
$formatted1 = $usa->format($number);
// $formatted2 is 1 234,56
// Note that it's a "non breaking space (\u00A0) between the 1 and the 2
$france = new NumberFormatter("fr-FR", NumberFormatter::DEFAULT_STYLE);
$formatted2 = $france->format($number);
Discussion
The number_format() function formats a number with decimal and thousands separators. By default, it rounds the number to the nearest integer. If you want to preserve the entire number, but you don’t know ahead of time how many digits follow the decimal point in your number, use this:$number = 31415.92653; // your number
list($int, $dec) = explode('.', $number);
// $formatted is 31,415.92653
$formatted = number_format($number, strlen($dec));
The NumberFormatter class, part of the intl extension, uses the extensive formatting rules that are part of the ICU library to give you an easy and powerful way to format numbers appropriately for anywhere in the world. You can even do fancy things such as spell out a number in words:
$number = '1234.56';
$france = new NumberFormatter("fr-FR", NumberFormatter::SPELLOUT);
// $formatted is "mille-deux-cent-trente-quatre virgule cinq six"
$formatted = $france->format($number);
No comments:
Post a Comment