2

I have an issue with number inputting. The user usually enters a large number with many zeros, and often they are missing one or two zero as it is difficult to accurately count them.

I think javascript can work this out by showing the user the number they have inducted, formatted with commas.

eg:

input: | 1230000000000 |

Result: 1,230,000,000,000

How could this be accomplished?

2
  • 1
    Java, or Javascript? Do you have a code example? Commented Apr 29, 2011 at 4:20
  • Are you making an application or is this an html form? Java and Javascript, despite the names, are very different in their style and common uses. Commented Apr 29, 2011 at 4:30

4 Answers 4

5

Use the following function in javascript

function addCommas(nStr)
{
    nStr += '';
    x = nStr.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');
    }
    return x1 + x2;
}

example

addCommas('9999999.00')
// 9,999,999.00
Sign up to request clarification or add additional context in comments.

1 Comment

-1 for same answer??? What to do, the two answers are in span of 2 mins. while I started to answer, there is no answer to this post and after I posted, I never checked back.. :)
1

This is an old question but still without a correct answer so, this is my dynamic solution, it takes the same addCommas function to reformat the output but add a keyup event to clean the current value ( remove ',' ) and reformat again the new value.

$('.datainto').keyup(function () {
    var value = $(this).val().replace(/,/g,'');
    $(this).val(addCommas(value));
});

Check the working solution here: http://jsfiddle.net/darorck/371zrjet/

1 Comment

One issue with this code is it doesn't let the user use their arrow keys and other keys that they could want to use. For example, if the user noticed that they messed up towards the beginning of the input and tried to use their left arrow key to go back to where they messed up, this code would keep bumping their cursor back to the end of the input. If you modify the anonymous function to accept "e", you could add something like this to the top: if ((e.keyCode >= 16 && e.keyCode <= 18) || (e.keyCode >= 33 && e.keyCode <= 40) || e.altKey || e.ctrlKey || e.shiftKey || e.metaKey) {return;}
1

function formatNumber() {
  // select the input box
  let numInput = document.getElementById("myNumberInput");

  //get the value from the selected input box, remove commas
  //and convert it into float
  let num = parseFloat(numInput.value.replace(/,/g, ""));

  //replace the value in the input box with comma separated value
  //only if it is a valid number
  if (!isNaN(num)) {
    let formattedNum = num.toLocaleString('en-US');
    numInput.value = formattedNum;
  } else {
    numInput.value = "";
  }
}
<input type="text" id="myNumberInput" onkeyup="formatNumber()" />

3 Comments

Hello! Thank you for posting your solution to the proposed problem! It would be great if you could edit your answer to include a bit more detail about what your code does and how it does it, so that people who come by it in the future can benefit from it.
Hi, please find the updated solution. I have added the necessary comments before each line so that it could be easily understood.
Thank you too for teaching me how to write good answers being a first timer!
0

In modern browsers, you can simply achieve this with toLocaleString()

console.log((1230000000000).toLocaleString());
console.log((12300000000).toLocaleString());
console.log((1230000.152).toLocaleString());

I know I'm very late for giving the answer, But still, I post this answer because this question is coming in the search result of How to add a dynamic comma in number in javascript, So I thought I need to add an answer which is shorter and better for upcoming developers.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.