-2

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.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
adit
  • 32,574
  • 72
  • 229
  • 373

2 Answers2

5
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. ;)

Community
  • 1
  • 1
Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
  • 1
    You got it slightly worng; dot is the thousand seporator and comma is the decimal seporator you could do: formatted = `value.toFixed(2).replace(".",",").replace(/\B(?=(\d{3})+(?!\d))/g, ".");` – HMR Jun 28 '13 at 04:32
  • @HMR - Not used to using `.` as the thousand separator :P And thanks for the suggestion for using `toFixed`. – Derek 朕會功夫 Jun 28 '13 at 04:34
0

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.

gustavohenke
  • 40,997
  • 14
  • 121
  • 129