Adding space between numbers
Asked Answered
C

4

86

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.

Carley answered 19/5, 2013 at 16:49 Comment(1)
A word of warning: This is really difficult to get right. What if I click with the mouse in the middle of the input and add a digit? What I move the cursor somewhere and hit Paste? How well will it work with Undo and Redo? There's a lot more to processing keyboard input than just accepting a correctly-type sequence of characters.Varus
S
174

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

Sneeze answered 19/5, 2013 at 17:3 Comment(2)
Great solution! Just need to replace 3 by 4 for Chinese numbers format.Flop
Would be good to see an explanation of the pattern.Resolved
F
98

Easiest way:

1

var num = 1234567890,
result = num.toLocaleString() ;// result will equal to "1 234 567 890"

2

var num = 1234567.890,
result = num.toLocaleString() + num.toString().slice(num.toString().indexOf('.')) // will equal to 1 234 567.890

3

var num = 1234567.890123,
result = Number(num.toFixed(0)).toLocaleString() + '.' + Number(num.toString().slice(num.toString().indexOf('.')+1)).toLocaleString()
//will equal to 1 234 567.890 123

4

If you want ',' instead of ' ':

var num = 1234567.890123,
result = Number(num.toFixed(0)).toLocaleString().split(/\s/).join(',') + '.' + Number(num.toString().slice(num.toString().indexOf('.')+1)).toLocaleString()
//will equal to 1,234,567.890 123

If not working, set the parameter like: "toLocaleString('ru-RU')" parameter "en-EN", will split number by the ',' instead of ' '

Formication answered 6/10, 2016 at 13:22 Comment(2)
great solution!Isolated
The first example only gives you spaces if you're in the same region. 'en-US' would display a comma instead, and it also depends on both browser and user settings. This is not a fool proof solution. https://mcmap.net/q/159843/-tolocalestring-not-supported-in-all-browsers-duplicateEmelun
R
0

This function works well inside an input:

const formatAndVerifyNumericValue = (value, callback) => {
const reg = new RegExp('^[0-9]+$');
let newValue = value.replace(/\s/g, '');
  if (reg.test(newValue)) {
   newValue = newValue.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+. 
     (?!\d))/g, ' ');
   return callback(newValue);
}}
Roland answered 27/10, 2021 at 7:8 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Glycol
S
-1

Try this

console.log(new Intl.NumberFormat().format(213294939493943.3242).replaceAll(',',' '))
Statolatry answered 26/9, 2023 at 15:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.