PHP Numbers Formatting Monetary Values - Web Development and Design | Tutorial for Java, PHP, HTML, Javascript PHP Numbers Formatting Monetary Values - Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Thursday, May 9, 2019

PHP Numbers Formatting Monetary Values

PHP Numbers





Formatting Monetary Values

Problem

You have a number and you want to print it with thousands and decimal separators. For instance, you want to display prices for items in a shopping cart.


Solution

Use the NumberFormatter class with the NumberFormatter::CURRENCY format style:

            $number = 1234.56;
            // US uses $ , and .
            // $formatted1 is $1,234.56
            $usa = new NumberFormatter("en-US", NumberFormatter::CURRENCY);
            $formatted1 = $usa->format($number);

            // France uses , and €
            // $formatted2 is 1 234,56 €
            $france = new NumberFormatter("fr-FR", NumberFormatter::CURRENCY);
            $formatted2 = $france->format($number);


Discussion

The NumberFormatter::CURRENCY format style formats a number by inserting the correct currency symbol, decimal, and thousands separators for the locale used to create the NumberFormatter object instance.

It assumes that the currency to use is the one native to the locale—US Dollars for the en-US locale, Euro for the fr-FR locale, and soon.

To produce the right format for a currency other than the locale’s native currency, use the formatCurrency() method. Its second argument lets you specify the currency to use. For example, what’s the correct way, in the USA, to format the price of something in Euro?

            $number = 1234.56;
            // US uses € , and . for Euro
            // $formatted is €1,234.56
           $usa = new NumberFormatter("en-US", NumberFormatter::CURRENCY);
           $formatted = $usa->formatCurrency($number, 'EUR');

ISO-4217 specifies the three-letter codes to use for the various currencies of Earth.



No comments:

Post a Comment

Post Top Ad