134

Is there any function in Javascript for formatting number and strings ?

I am looking for a way for thousand separator for string or numbers... (Like String.Format In c#)

Josh Stodola
  • 81,538
  • 47
  • 180
  • 227
LostLord
  • 2,279
  • 10
  • 32
  • 32
  • http://bytes.com/topic/c-sharp/answers/248039-formatcurrency-equiv – bevacqua Sep 20 '10 at 16:41
  • I think you'll find what you need in there :) http://stackoverflow.com/questions/610406/javascript-printf-string-format – Jad Sep 20 '10 at 16:41
  • `How to print a number with commas as thousands separators in JavaScript`: http://stackoverflow.com/questions/2901102/how-to-print-a-number-with-commas-as-thousands-separators-in-javascript – Adriano Dec 08 '16 at 15:44

15 Answers15

238

The reference cited in the original answer below was wrong. There is a built in function for this, which is exactly what kaiser suggests below: toLocaleString

So you can do:

(1234567.89).toLocaleString('en')              // for numeric input
parseFloat("1234567.89").toLocaleString('en')  // for string input

The function implemented below works, too, but simply isn't necessary.

(I thought perhaps I'd get lucky and find out that it was necessary back in 2010, but no. According to this more reliable reference, toLocaleString has been part of the standard since ECMAScript 3rd Edition [1999], which I believe means it would have been supported as far back as IE 5.5.)


Original Answer

According to this reference there isn't a built in function for adding commas to a number. But that page includes an example of how to code it yourself:

function addCommas(nStr) {
    nStr += '';
    var x = nStr.split('.');
    var x1 = x[0];
    var x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
            x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

Edit: To go the other way (convert string with commas to number), you could do something like this:

parseFloat("1,234,567.89".replace(/,/g,''))
isherwood
  • 58,414
  • 16
  • 114
  • 157
Tim Goodman
  • 23,308
  • 7
  • 64
  • 83
136

If is about localizing thousands separators, delimiters and decimal separators, go with the following:

// --> numObj.toLocaleString( [locales [, options] ] )
parseInt( number ).toLocaleString();

There are several options you can use (and even locales with fallbacks):

number = 123456.7089;

result  = parseInt( number ).toLocaleString() + "<br>";
result += number.toLocaleString( 'de-DE' ) + "<br>";
result += number.toLocaleString( 'ar-EG' ) + "<br>";
result += number.toLocaleString( 'ja-JP', { 
  style           : 'currency',
  currency        : 'JPY',
  currencyDisplay : 'symbol',
  useGrouping     : true
} ) + "<br>";
result += number.toLocaleString( [ 'jav', 'en' ], { 
  localeMatcher            : 'lookup',
  style                    : 'decimal',
  minimumIntegerDigits     : 2,
  minimumFractionDigits    : 2,
  maximumFractionDigits    : 3,
  minimumSignificantDigits : 2,
  maximumSignificantDigits : 3
} ) + "<br>";

var el = document.getElementById( 'result' );
el.innerHTML = result;
<div id="result"></div>

Details on the MDN info page.

Edit: Commentor @I like Serena adds the following:

To support browsers with a non-English locale where we still want English formatting, use value.toLocaleString('en'). Also works for floating point.

Community
  • 1
  • 1
kaiser
  • 21,817
  • 17
  • 90
  • 110
  • 1
    This not cover float nums.. you can change parseInt to parseFloat, but if yourInt = "100,12" (comma as decimal separator) this will fail. This can be fixed with a replace(",",".").. but will fail again with "1.000,12". So... You MUST reinvent the wheel sometimes. http://stackoverflow.com/a/2901298/1028304 – neiker Jul 24 '14 at 15:30
  • Does not work well. Uses comma while at our locale space is common for thousands separator. – Josef Sábl Sep 29 '14 at 15:56
  • Shame that toLocaleString() doesn't work correctly in Safari 8 (and possibly older). (1000).toLocaleString() returns "1000" rather than the expected "1,000". – Sam Potts Apr 07 '15 at 06:45
  • You can pass a locale to getLocaleString(): https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString – Sam Potts Apr 07 '15 at 06:50
  • 1
    This would be more appropriate: `Number(yourNumberOrString).toLocaleString()` – Jonathan Aug 17 '15 at 15:32
  • 2
    To support browsers with a non-English locale where we still want English formatting, use `value.toLocaleString('en')`. Also works for floating point. – Klaas van Aarsen Sep 12 '15 at 21:54
  • 1
    @Serhiog.Lazin _What exactly_ does not work on Safari (and on which OS and in which version)? – kaiser Jan 06 '16 at 16:37
  • 4
    FYI, For India number format like ```7,77,77,777```, use ```value.toLocaleString('en-IN')``` – Makesh Sep 17 '20 at 11:22
48

Updated using look-behind support in line with ECMAScript2018 changes.
For backwards compatibility, scroll further down to see the original solution.

A regular expression may be used - notably useful in dealing with big numbers stored as strings.

const format = num => 
    String(num).replace(/(?<!\..*)(\d)(?=(?:\d{3})+(?:\.|$))/g, '$1,')

;[
    format(100),                           // "100"
    format(1000),                          // "1,000"
    format(1e10),                          // "10,000,000,000"  
    format(1000.001001),                   // "1,000.001001"
    format('100000000000000.001001001001') // "100,000,000,000,000.001001001001
]
    .forEach(n => console.log(n))

» Verbose regex explanation (regex101.com) flow diagram


This original answer may not be required but can be used for backwards compatibility.

Attempting to handle this with a single regular expression (without callback) my current ability fails me for lack of a negative look-behind in Javascript... never the less here's another concise alternative that works in most general cases - accounting for any decimal point by ignoring matches where the index of the match appears after the index of a period.

const format = num => {
    const n = String(num),
          p = n.indexOf('.')
    return n.replace(
        /\d(?=(?:\d{3})+(?:\.|$))/g,
        (m, i) => p < 0 || i < p ? `${m},` : m
    )
}

;[
    format(100),                           // "100"
    format(1000),                          // "1,000"
    format(1e10),                          // "10,000,000,000"  
    format(1000.001001),                   // "1,000.001001"
    format('100000000000000.001001001001') // "100,000,000,000,000.001001001001
]
    .forEach(n => console.log(n))

» Verbose regex explanation (regex101.com)

flow diagram

Emissary
  • 9,954
  • 8
  • 54
  • 65
  • Has this syntax diagram been created on regex101.com? – Gerold Broser Apr 19 '17 at 23:26
  • what happen with numbers with decimals? – Emiliano Dec 18 '19 at 14:53
  • I'm getting "Invalid regular expression: invalid group specifier name". On React Native 0.59 doing this but that really shouldn't affect RegEx. – Joshua Pinter Jan 10 '20 at 16:56
  • @JoshuaPinter It'll be the use of look-behind which at time of writing is not yet supported across all platforms. I'm guessing you're referring specifically to iOS - as Safari still fails for me too. It may be best to stick with the backward compatible version for now. I was just trying to future-proof my answer. https://caniuse.com/#search=lookbehind – Emissary Jan 12 '20 at 19:42
  • 1
    @Emissary Thanks for the tip. Yeah, it's on React Native 0.59 / Android, which uses a relatively older version of JavaScriptCore (JSC). I'll try again after we update to React Native 0.60+, which includes an update to the JSC. – Joshua Pinter Jan 12 '20 at 23:15
  • Not working in edge, it's giving "Unexpected quantifier" – Mahendra Jella Apr 01 '20 at 11:56
  • @LeadDeveloper It works in the latest version (79 / 80) - literally only introduced in the last month or so. Maybe try forcing a browser update? – Emissary Apr 01 '20 at 22:20
11

There's a nice jQuery number plugin: https://github.com/teamdf/jquery-number

It allows you to change any number in the format you like, with options for decimal digits and separator characters for decimal and thousand:

$.number(12345.4556, 2);          // -> 12,345.46
$.number(12345.4556, 3, ',', ' ') // -> 12 345,456

You can use it inside input fields directly, which is nicer, using same options like above:

$("input").number(true, 2);

Or you can apply to a whole set of DOM elements using selector:

$('span.number').number(true, 2);
qdev
  • 1,371
  • 1
  • 15
  • 18
6

I use this:

function numberWithCommas(number) {
    return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

source: link

Abhishek Goel
  • 18,785
  • 11
  • 87
  • 65
  • `'123452343267.0505'.replace(/\B(?=(\d{3})+(?!\d))/g, ","); "123,452,343,267.0,505"` - notice that last comma after the decimal point. – hippietrail Oct 03 '17 at 00:53
6
var number = 35002343;

console.log(number.toLocaleString());

for the reference you can check here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString

vikashraj144
  • 73
  • 1
  • 8
5
// thousand separates a digit-only string using commas
// by element:  onkeyup = "ThousandSeparate(this)"
// by ID:       onkeyup = "ThousandSeparate('txt1','lbl1')"
function ThousandSeparate()
{
    if (arguments.length == 1)
    {
        var V = arguments[0].value;
        V = V.replace(/,/g,'');
        var R = new RegExp('(-?[0-9]+)([0-9]{3})'); 
        while(R.test(V))
        {
            V = V.replace(R, '$1,$2');
        }
        arguments[0].value = V;
    }
    else  if ( arguments.length == 2)
    {
        var V = document.getElementById(arguments[0]).value;
        var R = new RegExp('(-?[0-9]+)([0-9]{3})'); 
        while(R.test(V))
        {
            V = V.replace(R, '$1,$2');
        }
        document.getElementById(arguments[1]).innerHTML = V;
    }
    else return false;
}   
Chris Frederick
  • 5,482
  • 3
  • 36
  • 44
h.foroutan
  • 51
  • 1
  • 2
3

All you need to do is just really this:

123000.9123.toLocaleString()
//result will be "123,000.912"
ey dee ey em
  • 7,991
  • 14
  • 65
  • 121
  • Unfortunately it depends on your platform. Some have a `toLocaleString()` which does not add the commas, or lacks other features in the standard. It's easy to check for `toLocaleString` presence but not to check for its compliance. – hippietrail Oct 03 '17 at 00:56
  • try with a number between 1000 and 9999 – Emiliano Dec 18 '19 at 14:44
3

You can use javascript. below are the code, it will only accept numeric and one dot

here is the javascript

<script >

            function FormatCurrency(ctrl) {
                //Check if arrow keys are pressed - we want to allow navigation around textbox using arrow keys
                if (event.keyCode == 37 || event.keyCode == 38 || event.keyCode == 39 || event.keyCode == 40) {
                    return;
                }

                var val = ctrl.value;

                val = val.replace(/,/g, "")
                ctrl.value = "";
                val += '';
                x = val.split('.');
                x1 = x[0];
                x2 = x.length > 1 ? '.' + x[1] : '';

                var rgx = /(\d+)(\d{3})/;

                while (rgx.test(x1)) {
                    x1 = x1.replace(rgx, '$1' + ',' + '$2');
                }

                ctrl.value = x1 + x2;
            }

            function CheckNumeric() {
                return event.keyCode >= 48 && event.keyCode <= 57 || event.keyCode == 46;
            }

  </script>

HTML

<input type="text" onkeypress="return CheckNumeric()" onkeyup="FormatCurrency(this)" />

DEMO JSFIDDLE

Awtszs
  • 323
  • 1
  • 8
  • 33
3
number = 123456.7089;
result = parseInt( number ).toLocaleString() + "<br>";
result = number.toLocaleString( 'pt-BR' ) + "<br>";

var el = document.getElementById( 'result' );
el.innerHTML = result;
<div id="result"></div>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Ricardo
  • 31
  • 1
3

PHP.js has a function to do this called number_format. If you are familiar with PHP it works exactly the same way.

istvanp
  • 4,423
  • 3
  • 24
  • 26
2

You can use the following function:

function format(number, decimals = 2, decimalSeparator = '.', thousandsSeparator = ',') {
  const roundedNumber = number.toFixed(decimals);
  let integerPart = '',
    fractionalPart = '';
  if (decimals == 0) {
    integerPart = roundedNumber;
    decimalSeparator = '';
  } else {
    let numberParts = roundedNumber.split('.');
    integerPart = numberParts[0];
    fractionalPart = numberParts[1];
  }
  integerPart = integerPart.replace(/(\d)(?=(\d{3})+(?!\d))/g, `$1${thousandsSeparator}`);
  return `${integerPart}${decimalSeparator}${fractionalPart}`;
}

// Use Example

let min = 1556454.0001;
let max = 15556982.9999;

console.time('number format');
for (let i = 0; i < 15; i++) {
  let randomNumber = Math.random() * (max - min) + min;
  let formated = format(randomNumber, 4, ',', '.'); // formated number

  console.log('number: ', randomNumber, '; formated: ', formated);
}
console.timeEnd('number format');
jin_maxtor
  • 31
  • 3
  • Don't make it so confusing. just use toLocaleString(). More information in https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString – S.Saderi May 25 '20 at 04:34
  • @sajadsaderi I also use toLocaleString () friend, but this function doesn't give me much flexibility, so I don't have to be dealing with regional abbreviations and someone else could use it since the definition of this function is identical to the number_format () function of php. – jin_maxtor May 25 '20 at 22:18
1

Combination of solutions for react

  let converter = Intl.NumberFormat();
  let salary =  monthlySalary.replace(/,/g,'')
  console.log(converter.format(salary))
  
  this.setState({
    monthlySalary: converter.format(salary)
  })
}

handleOnChangeMonthlySalary(1000)
SwissCodeMen
  • 4,222
  • 8
  • 24
  • 34
Chinedu Ofor
  • 707
  • 9
  • 11
0

I did not like any of the answers here, so I created a function that worked for me. Just want to share in case anyone else finds it useful.

function getFormattedCurrency(num) {
    num = num.toFixed(2)
    var cents = (num - Math.floor(num)).toFixed(2);
    return Math.floor(num).toLocaleString() + '.' + cents.split('.')[1];
}
Spencer Sullivan
  • 527
  • 6
  • 13
0

You can use ngx-format-field. It is a directive to format the input value which will appear in the view. It will not manipulate the Input value which will be saved in the backend. See link here!

Example:

component.html:

<input type="text" formControlName="currency" [appFormatFields]="CURRENCY"
(change)="onChangeCurrency()">

component.ts

onChangeCurrency() {
this.currency.patchValue(this.currency.value);
}

To see the demo: here!