在数字之间添加空格 [英] Adding space between numbers

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

问题描述

我正在尝试输入数字.我已经做完了,所以我的文本框仅通过以下代码接受数字:

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;
}

但是现在问题来了,当用户输入数字时,我将如何创建空格,就像iPhone的电话间隔一样,但是如果输入数字,例如,如果输入:1000,它将变成1000;如果输入数字,则将如何创建空格.

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

等等...

我尝试从右边读取每个3个字符的输入,并添加一个空格.但是我的方法效率低下,当我在文本框中将值从1000更改为1000时,由于某种原因它选择了它,然后再按任意键,就擦除了整个内容.

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.

如果您知道该怎么做,请不要使用jQuery之类的JavaScript插件.谢谢.

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

推荐答案

对于整数,请使用

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(".");
}

这是一个简单的正则表达式工作. https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Regular_Expressions <<在此处找到有关Regex的更多信息.

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆