This requires two operations...

  1. Parse the number string into a Number instance

    const actualNumber = +number.replace(/,/g, '') // produces 4500.02734
    
  2. Format the string to a given locale with a maximum of 2 decimal places

    const formatted = actualNumber.toLocaleString('en-US', {maximumFractionDigits: 2})
    

var number = '4,500.02734'

const actualNumber = +number.replace(/,/g, '')
const formatted = actualNumber.toLocaleString('en-US', {maximumFractionDigits: 2})

document.write(formatted)

Answer from Phil on Stack Overflow
🌐
DotNetCurry
dotnetcurry.com › jquery › 1076 › using-jquery-add-commmas-numbers-textbox
Automatically add Commas to a Number in a TextBox | DotNetCurry
The script uses a regular expression to add commas. Passing a number like 23456789.12345 produces 23,456,789.12345, which is the desired result. Live Demo: http://www.jquerycookbook.com/demos/S2-InputControls/12-NumberFormatting.html · The script we saw works fine, but what if at a later date, ...
🌐
ASPSnippets
aspsnippets.com › questions › 138804 › Format-string-number-with-commas-and-two-decimals-in-jQuery › answers
Format string number with commas and two decimals in jQuery
August 27, 2024 - <input id="txtNumber" type="text" value="1200900,56" /> <input id="btnSubmit" type="button" value="Submit" /> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <script type="text/javascript"> $(function () { $("#btnSubmit").click(function () { var parts = $("#txtNumber").val().split(','); parts[0] = parseFloat(parts[0].replace(/\D/g, "")).toLocaleString('de-DE'); $("#txtNumber").val(parts[0] + (parts[1] ?
🌐
Medium
medium.com › @noffybarudwale › javascript-format-numbers-with-commas-and-decimals-86b68ec5b180
JavaScript : Format numbers with commas and decimals. | by Nofij Barudwale | Medium
October 13, 2021 - Sometimes, you may need to format a number value with commas and decimals in your HTML pages to make it easier to read. Here I found both in one. You can transform a number value into a comma-separated with decimals by using JavaScript.
🌐
CSS-Tricks
css-tricks.com › snippets › javascript › comma-values-in-numbers
Put Comma Values in Numbers | CSS-Tricks
December 19, 2009 - Any reason not to just use ... places. ... Javascript has a method called toFixed() that will format your numbers so they have commas and even let you add 2 decimals....
🌐
EyeHunts
tutorial.eyehunts.com › home › javascript format number with commas and decimal places | example
JavaScript format number with commas and decimal places | Code
December 13, 2022 - // With custom settings, forcing a "US" locale to guarantee commas in output let number2 = 1234.56789; // floating point example number2.toLocaleString('en-US', {maximumFractionDigits:2}) // "1,234.57"
🌐
GitHub
github.com › customd › jquery-number
GitHub - customd/jquery-number: Easily format numbers for display use. Replace numbers inline in a document, or return a formatted number for other uses.
Decimal Separator: The character(s) to use as a decimal separator. Defaults to '.'. ... Thousands Separator: The character(s) to use as a thousands separator. Defaults to ','. $.number( 5020.2364, 1, ',', ' ' ); // Outputs: 5 020,2
Starred by 443 users
Forked by 388 users
Languages   JavaScript 100.0% | JavaScript 100.0%
Find elsewhere
🌐
CodePen
codepen.io › engza › pen › jOyOYK
jQuery Add Commas to Numbers
function numberWithCommas(number) { var parts = number.toString().split("."); parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ","); return parts.join("."); } $(document).ready(function() { $("#agent_commission_model td").each(function() ...
🌐
FoxLearn
foxlearn.com › javascript › how-to-format-number-with-commas-and-decimal-in-javascript-603.html
How to format number with commas and decimal in Javascript
... You can use regular expression to solve the problem. var value =1234.542 var parts = value.toFixed(2).split("."); var num = parts[0].replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,") + (parts[1] ?
🌐
IQCode
iqcode.com › code › javascript › jquery-number-format-comma
jquery number format comma Code Example
var number = 1557564534; document.body.innerHTML = number.toLocaleString(); // 1,557,564,534
Top answer
1 of 2
12

Could do this, but what I would do instead is show the comma separated number elsewhere besides the input field.

$('input.number').keyup(function(event) {

  // skip for arrow keys
  if(event.which >= 37 && event.which <= 40){
   event.preventDefault();
  }

  $(this).val(function(index, value) {
      value = value.replace(/,/g,''); // remove commas from existing input
      return numberWithCommas(value); // add commas back in
  });
});

function numberWithCommas(x) {
    var parts = x.toString().split(".");
    parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    return parts.join(".");
}

http://jsfiddle.net/jpAmE/

2 of 2
10

I think this might do what you are looking for. Assumptions:

  1. Users are only allowed to enter one decimal point.
  2. no formatting is allowed after the decimal point, i.e. commas.

Fiddle

$('input.number').keyup(function (event) {
    // skip for arrow keys
    if (event.which >= 37 && event.which <= 40) {
        event.preventDefault();
    }

    var currentVal = $(this).val();
    var testDecimal = testDecimals(currentVal);
    if (testDecimal.length > 1) {
        console.log("You cannot enter more than one decimal point");
        currentVal = currentVal.slice(0, -1);
    }
    $(this).val(replaceCommas(currentVal));
});

function testDecimals(currentVal) {
    var count;
    currentVal.match(/\./g) === null ? count = 0 : count = currentVal.match(/\./g);
    return count;
}

function replaceCommas(yourNumber) {
    var components = yourNumber.toString().split(".");
    if (components.length === 1)
        components[0] = yourNumber;
    components[0] = components[0].replace(/\D/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    if (components.length === 2)
        components[1] = components[1].replace(/\D/g, "");
    return components.join(".");
}
🌐
Stack Abuse
stackabuse.com › bytes › format-numbers-with-commas-in-javascript
Format Numbers with Commas in JavaScript
August 7, 2023 - However, keep in mind that toLocaleString() will keep all digits after the decimal. So 1234567.890123 would become "1,234,567.890123". If you need a bit more control over the formatting, regular expressions can help: function formatNumberWithCommas(number) { return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); } const number = 1234567.89; console.log(formatNumberWithCommas(number)); // Outputs: "1,234,567.89" Link: This function uses regular expressions to insert commas after every third digit from right to left, providing the desired formatting.
🌐
Stack Overflow
stackoverflow.com › questions › 23301201 › formatting-and-adding-decimals-commas-in-jquery
Formatting and adding decimals, commas in JQUERY
This regex will add the appropriate commas to a number. var $total = $val1 - $val2 - $val3 - $val4 - $val5 - $val6 - $val7 - $val8 - $val9 - $val10 - $val11 - $val12; $total = $total.toFixed(2); $total = $total.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); $('.totalbudget', this).text($total);