Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding space between numbers

I'm trying to make a number input. I've made so my textbox only accepts numbers via this code:

function isNumber(evt) {     evt = (evt) ? evt : window.event;     var charCode = (evt.which) ? evt.which : evt.keyCode;     if (charCode > 31 && (charCode < 48 || charCode > 57)) {         return false;     }     return true; } 

But now the question comes to, how would I create spaces as the user is typing in their number, much like the iPhone's telephone spacing thing, but with numbers so for example if they type in: 1000 it will become 1 000;

1 10 100 1 000 10 000 100 000 1 000 000 10 000 000 100 000 000 1 000 000 000 

Etc...

I've tried to read the input from the right for each 3 characters and add a space. But my way is inefficient and when I'm changing the value from 1000 to 1 000 in the textbox, it selects it for some reason, making any key press after that, erase the whole thing.

If you know how to do this, please refrain from using javascript plugins like jQuery. Thank You.

like image 664
user1768788 Avatar asked May 19 '13 16:05

user1768788


People also ask

How do I add a space between two cells in Excel?

If your cell has white space, and you want to increase the line space to fill it evenly, change the vertical spacing to Justify. Right-click in the cell you want, and click Format cells. On the Alignment tab, change Vertical to Justify. Click OK.


1 Answers

For integers use

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

For floating point numbers you can use

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

This is a simple regex work. https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Regular_Expressions << Find more about Regex here.

If you are not sure about whether the number would be integer or float, just use 2nd one...

like image 115
Isham Mohamed Avatar answered Oct 09 '22 01:10

Isham Mohamed