[javascript] Javascript Thousand Separator / string format

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#)

This question is related to javascript string numbers format

The answer is


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>

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):

_x000D_
_x000D_
number = 123456.7089;_x000D_
_x000D_
result  = parseInt( number ).toLocaleString() + "<br>";_x000D_
result += number.toLocaleString( 'de-DE' ) + "<br>";_x000D_
result += number.toLocaleString( 'ar-EG' ) + "<br>";_x000D_
result += number.toLocaleString( 'ja-JP', { _x000D_
  style           : 'currency',_x000D_
  currency        : 'JPY',_x000D_
  currencyDisplay : 'symbol',_x000D_
  useGrouping     : true_x000D_
} ) + "<br>";_x000D_
result += number.toLocaleString( [ 'jav', 'en' ], { _x000D_
  localeMatcher            : 'lookup',_x000D_
  style                    : 'decimal',_x000D_
  minimumIntegerDigits     : 2,_x000D_
  minimumFractionDigits    : 2,_x000D_
  maximumFractionDigits    : 3,_x000D_
  minimumSignificantDigits : 2,_x000D_
  maximumSignificantDigits : 3_x000D_
} ) + "<br>";_x000D_
_x000D_
var el = document.getElementById( 'result' );_x000D_
el.innerHTML = result;
_x000D_
<div id="result"></div>
_x000D_
_x000D_
_x000D_

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.


// 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;
}   

You can use the following function:

_x000D_
_x000D_
function format(number, decimals = 2, decimalSeparator = '.', thousandsSeparator = ',') {_x000D_
  const roundedNumber = number.toFixed(decimals);_x000D_
  let integerPart = '',_x000D_
    fractionalPart = '';_x000D_
  if (decimals == 0) {_x000D_
    integerPart = roundedNumber;_x000D_
    decimalSeparator = '';_x000D_
  } else {_x000D_
    let numberParts = roundedNumber.split('.');_x000D_
    integerPart = numberParts[0];_x000D_
    fractionalPart = numberParts[1];_x000D_
  }_x000D_
  integerPart = integerPart.replace(/(\d)(?=(\d{3})+(?!\d))/g, `$1${thousandsSeparator}`);_x000D_
  return `${integerPart}${decimalSeparator}${fractionalPart}`;_x000D_
}_x000D_
_x000D_
// Use Example_x000D_
_x000D_
let min = 1556454.0001;_x000D_
let max = 15556982.9999;_x000D_
_x000D_
console.time('number format');_x000D_
for (let i = 0; i < 15; i++) {_x000D_
  let randomNumber = Math.random() * (max - min) + min;_x000D_
  let formated = format(randomNumber, 4, ',', '.'); // formated number_x000D_
_x000D_
  console.log('number: ', randomNumber, '; formated: ', formated);_x000D_
}_x000D_
console.timeEnd('number format');
_x000D_
_x000D_
_x000D_


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


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];
}

All you need to do is just really this:

123000.9123.toLocaleString()
//result will be "123,000.912"

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)```

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.

_x000D_
_x000D_
const format = num => _x000D_
    String(num).replace(/(?<!\..*)(\d)(?=(?:\d{3})+(?:\.|$))/g, '$1,')_x000D_
_x000D_
;[_x000D_
    format(100),                           // "100"_x000D_
    format(1000),                          // "1,000"_x000D_
    format(1e10),                          // "10,000,000,000"  _x000D_
    format(1000.001001),                   // "1,000.001001"_x000D_
    format('100000000000000.001001001001') // "100,000,000,000,000.001001001001_x000D_
]_x000D_
    .forEach(n => console.log(n))
_x000D_
_x000D_
_x000D_

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

_x000D_
_x000D_
const format = num => {_x000D_
    const n = String(num),_x000D_
          p = n.indexOf('.')_x000D_
    return n.replace(_x000D_
        /\d(?=(?:\d{3})+(?:\.|$))/g,_x000D_
        (m, i) => p < 0 || i < p ? `${m},` : m_x000D_
    )_x000D_
}_x000D_
_x000D_
;[_x000D_
    format(100),                           // "100"_x000D_
    format(1000),                          // "1,000"_x000D_
    format(1e10),                          // "10,000,000,000"  _x000D_
    format(1000.001001),                   // "1,000.001001"_x000D_
    format('100000000000000.001001001001') // "100,000,000,000,000.001001001001_x000D_
]_x000D_
    .forEach(n => console.log(n))
_x000D_
_x000D_
_x000D_

» Verbose regex explanation (regex101.com)

flow diagram


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!


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


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

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


I use this:

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

source: link


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to numbers

how to display a javascript var in html body How to label scatterplot points by name? Allow 2 decimal places in <input type="number"> Why does the html input with type "number" allow the letter 'e' to be entered in the field? Explanation on Integer.MAX_VALUE and Integer.MIN_VALUE to find min and max value in an array Input type "number" won't resize C++ - how to find the length of an integer How to Generate a random number of fixed length using JavaScript? How do you check in python whether a string contains only numbers? Turn a single number into single digits Python

Examples related to format

Brackets.io: Is there a way to auto indent / format <html> Oracle SQL - DATE greater than statement What does this format means T00:00:00.000Z? How to format date in angularjs How do I change data-type of pandas data frame to string with a defined format? How to pad a string to a fixed length with spaces in Python? How to format current time using a yyyyMMddHHmmss format? java.util.Date format SSSSSS: if not microseconds what are the last 3 digits? Formatting a double to two decimal places How enable auto-format code for Intellij IDEA?