密钥的格式量

时间:2012-11-30 20:47:22

标签: javascript onkeyup

我想在keyup javascript事件上格式化数量。我需要这样的结果:

  • 100> 100
  • 1000> 1 000
  • 100000000> 100 000 000
  • 1000,12> 1 000,12
你能帮帮我吗?

3 个答案:

答案 0 :(得分:0)

你需要这样的东西:

function formatNumber(numberString) {
    var commaIndex = numberString.indexOf(',');
    var int = numberString;
    var frac = '';

    if (~commaIndex) {
        int = numberString.slice(0, commaIndex);
        frac = ',' + numberString.slice(commaIndex + 1);
    }

    var firstSpanLength = int.length % 3;
    var firstSpan = int.slice(0, firstSpanLength);
    var result = [];

    if (firstSpan) {
        result.push(firstSpan);
    }

    int = int.slice(firstSpanLength);

    var restSpans = int.match(/\d{3}/g);

    if (restSpans) {
        result = result.concat(restSpans);
        return result.join(' ') + frac;
    }

    return firstSpan + frac;
}

formatNumber('1234567890,12'); // "1 234 567 890,12"

将它与事件监听器一起使用,并将此函数发送给表示数字的字符串,它将以所需格式返回字符串

input.onkeyup = function () {
    input.value = input.value.replace(/\d+(?:,\d+)?/g, formatNumber);
};

答案 1 :(得分:0)

function formatNumberField() {
    // unformat the value
    var value = this.value.replace(/[^\d,]/g, '');

    // split value into (leading digits, 3*x digits, decimal part)
    // also allows numbers like ',5'; if you don't want that,
    // use /^(\d{1,3})((?:\d{3})*))((?:,\d*)?)$/ instead
    var matches = /^(?:(\d{1,3})?((?:\d{3})*))((?:,\d*)?)$/.exec(value);

    if (!matches) {
        // invalid format; deal with it however you want to
        // this just stops trying to reformat the value
        return;
    }

    // add a space before every group of three digits
    var spaceified = matches[2].replace(/(\d{3})/g, ' $1');

    // now splice it all back together
    this.value = [matches[1], spaceified, matches[3]].join('');
}

// attaching event handler with jQuery...
$(document).ready(function() {
    $('#your-element-id').on('keyup', formatNumberField);
});

// With vanilla JS, it can get a little ugly.  This is the simplest way that
// will work in pretty much all browsers.
// Stick this in your "dom is loaded" callback
document.getElementById('your-element-id').onkeyup = formatNumberField;

答案 2 :(得分:0)

这是一个古怪的格式函数,很有思考:

function formatNumber(s) {
  var parts = s.split(/,/)
    , spaced = parts[0]
         .split('').reverse().join('') // Reverse the string.
         .match(/\d{1,3}/g).join(' ') // Join groups of 3 digits with spaces.
         .split('').reverse().join(''); // Reverse it back.
  return spaced + (parts[1] ? ','+parts[1] : ''); // Add the fractional part.
}

您可以使用纯JavaScript中的element.addEventListener(...)或jQuery中的.on(...)函数将其附加到元素的“keyup”事件中,例如:

$('.my-input').on('keyup', function() {
  var $this = $(this);
  $this.val(formatNumber($this.val());
});