在数字之间添加空格

在数字之间添加空格

本文介绍了在数字之间添加空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试输入数字。我做了这样我的文本框只接受通过此代码的数字:

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

但现在问题出现了,我将如何创建空格,因为用户是输入他们的电话号码,就像iPhone的电话号码一样,但输入的数字是:例如输入1000:1000就会变成1000;

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

等...



我试着从右侧读取每个3个字符的输入并添加一个空格。但我的方式效率低下,当我在文本框中将值从1000更改为1000时,它会因为某种原因选择它,然后在此之后进行任何按键操作,将整个项目擦除。



如果您知道如何做到这一点,请避免使用jQuery等javascript插件。

解决方案

对于整数使用

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

对于浮点数,您可以使用

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

这是一个简单的正则表达式工作。 <<如果你不确定这个数字是整数还是浮点数,只需使用第二个...


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.

解决方案

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

这篇关于在数字之间添加空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 09:09