Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a PHP function equivalent to JavaScript function toLocaleString()

Tags:

javascript

php

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.

like image 927
Rohit Kapali Avatar asked Feb 25 '18 07:02

Rohit Kapali


3 Answers

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

like image 100
Mike Stratton Avatar answered Oct 08 '22 20:10

Mike Stratton


use

$x = 45604586;
number_format($x);

output: 45,604,586

like image 36
AmirHossein Mahmoodi Avatar answered Oct 08 '22 20:10

AmirHossein Mahmoodi


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
like image 38
Giorgio Tempesta Avatar answered Oct 08 '22 20:10

Giorgio Tempesta