5

I was looking for a pre-built number formatting function and came across this JS function toLocaleString(). This function does exactly what I want it to do.

For example, I have a number which I want to be formatted, let's say 1234567890.123. I want this number to be formatted into 1,23,45,67,890.123 & 1,234,567,890.123.

With the JS function I did it like this and got the desired output

var number = 1234567890.123;
number.toLocaleString('hi-IN'); //1,23,45,67,890.123
number.toLocaleString('en'); //1,234,567,890.123

However, I wanted to know if there is a built in method to do this with PHP.

NOTE: money_format() is not what I'm looking for and I just want to know if there exists such a function in PHP too. If not, no problem, I'll have to write a custom function.

Rohit Kapali
  • 216
  • 3
  • 10
  • 1
    Check the [Internationalization Functions](http://php.net/manual/en/book.intl.php), probably a class for whatever you might need, like [NumberFormatter](http://php.net/manual/en/class.numberformatter.php) – Patrick Evans Feb 25 '18 at 07:44

3 Answers3

3

PHP does allow for Number Formatting, but does not have a function that can do exactly as Javascript's toLocaleString().

The best equivelant is provided here: How to display Currency in Indian Numbering Format in PHP

PHP's NumberFormatter can be used to format decimals. The JavaScript implementation sets the locale value on the client side of the browser and then outputs the results.

PHP has a similar method for setting the locale value, but is performed on the server. This could result in unintended consequences.

"Warning: The locale information is maintained per process, not per thread. If you are running PHP on a multithreaded server API like IIS, HHVM or Apache on Windows, you may experience sudden changes in locale settings while a script is running, though the script itself never called setlocale(). This happens due to other scripts running in different threads of the same process at the same time, changing the process-wide locale using setlocale()." Source: http://php.net/manual/en/function.setlocale.php

Mike Stratton
  • 463
  • 1
  • 7
  • 20
  • Hi Mike, thank you for your response. I had already checked the Currency question before making this post. It does produce the desired output to some extent but not exactly what I wanted. I just wanted to know if there was any function which could do exactly what toLocaleString() does. Seems like not. Thanks. – Rohit Kapali Feb 25 '18 at 09:29
3

use

$x = 45604586;
number_format($x);

output: 45,604,586

2

Following the link about The NumberFormatter class in this answer I was able to make the exact things I do with toLocaleString() in JavaScript:

$locale = 'en';
$currency = 'EUR';
$price = 45604586;
$fmt = new NumberFormatter($locale, NumberFormatter::CURRENCY);
$formattedPrice = $fmt->formatCurrency($price, $currency);
echo $formattedPrice;

It prints:

€45,604,586.00
Giorgio Tempesta
  • 1,816
  • 24
  • 32