-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.

7
  • 4
    If you don't want to use any plugin - why did you mention jquery? Commented Jun 28, 2013 at 4:19
  • 1
    @zerkms I mean using built in jQuery function, nothing else Commented Jun 28, 2013 at 4:21
  • 1
    @adit: have you checked api.jquery.com for available functions? Commented Jun 28, 2013 at 4:21
  • 1
    stackoverflow.com/questions/10809136/… Commented Jun 28, 2013 at 4:21
  • 1
    Then Derek has already answered the question using a regexp. From his answer with a slight change: console.log(value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".")+",00"); Commented Jun 28, 2013 at 4:28

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

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 - Not used to using . as the thousand separator :P And thanks for the suggestion for using toFixed.
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.