I have a number such as 50000 in the following variable:
var i = 50000
and I want to format it as a string such that it prints out 50.000,00 . What is the easiest way in jQuery to do this aside from using a plugin, such as the numbers plugin.
I have a number such as 50000 in the following variable:
var i = 50000
and I want to format it as a string such that it prints out 50.000,00 . What is the easiest way in jQuery to do this aside from using a plugin, such as the numbers plugin.
var value = 50000.69,
formatted = value.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
console.log(formatted);
Native JavaScript, and you don't even need jQuery or any plugin. Very flexible as you can modify the regex however you want.
As HMR mentioned, use the following code for your specified format:
formatted = value.replace(".",",").replace(/\B(?=(\d{3})+(?!\d))/g, ".");
Add .toFixed(
2
)
if you want a maximum of 2 digits after the decimal point, but I'm sure you get it. ;)
You could try the JS version of the PHP function number_format
, by the PHP.js project:
http://phpjs.org/functions/number_format/
number_format(50000, 2, ',', '.');
It's very flexible, if that's something you're going to need.
Another way is to use or base yourself in the underscore.string approach, which actually looks like PHP.js's one.