仅使用Java脚本将数字格式化为千 [英] Formatting number as thousand using only Javascript

查看:70
本文介绍了仅使用Java脚本将数字格式化为千的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Console.log显示的是正确的结果,但是在键入时如何在输入类型中添加相同的格式.

Console.log is showing the correct result, but how can I add the same formatting to the input type while typing.

每个逗号都清零后,输入类型将重置.

Input type is reset after every comma to zero.

1000至1,000

1000 to 1,000

请帮助.

此代码有效此处

function numberWithCommas(number) {
    if (isNaN(number)) {
        return '';
    }

    var asString = '' + Math.abs(number),
        numberOfUpToThreeCharSubstrings = Math.ceil(asString.length / 3),
        startingLength = asString.length % 3,
        substrings = [],
        isNegative = (number < 0),
        formattedNumber,
        i;

    if (startingLength > 0) {
        substrings.push(asString.substring(0, startingLength));
    }

    for (i=startingLength; i < asString.length; i += 3) {
        substrings.push(asString.substr(i, 3));
    }

    formattedNumber = substrings.join(',');

    if (isNegative) {
        formattedNumber = '-' + formattedNumber;
    }

    document.getElementById('test').value = formattedNumber;
}

<input type="number" id="test" class="test" onkeypress="numberWithCommas(this.value)">

推荐答案

一些注意事项:

  • 因为要用逗号,所以类型不是数字,而是字符串
  • 由于您要在输入后处理输入,因此它是onkeyup而不是onkeypressed

我有一个解决方案,可将正则表达式替换为3个字符和3个字符,再加上一个逗号:

I have a solution that does a regex replace for 3 characters with 3 characters PLUS a comma:

var x = "1234567";
x.replace(/.../g, function(e) { return e + ","; } );
// Gives: 123,456,7

即几乎是正确的答案,但是逗号不在正确的位置.因此,让我们使用String.prototype.reverse()函数对其进行修复:

i.e. almost the right answer, but the commas aren't in the right spot. So let's fix it up with a String.prototype.reverse() function:

String.prototype.reverse = function() {
    return this.split("").reverse().join("");
}

function reformatText() {
    var x = document.getElementById('test').value;
    x = x.replace(/,/g, ""); // Strip out all commas
    x = x.reverse();
    x = x.replace(/.../g, function(e) { return e + ","; } ); // Insert new commas
    x = x.reverse();
    x = x.replace(/^,/, ""); // Remove leading comma
    document.getElementById('test').value = x;
}

<input id="test" class="test" onkeyup="reformatText()">

这篇关于仅使用Java脚本将数字格式化为千的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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