【问题标题】:Format amount on keyupkeyup 上的格式数量
【发布时间】:2012-11-30 20:47:21
【问题描述】:

我想在 keyup javascript 事件中格式化金额。我需要这样的结果:

  • 100 > 100
  • 1000 > 1 000
  • 100000000 > 100 000 000
  • 1000,12 > 1 000,12

你能帮帮我吗?

【问题讨论】:

  • 我尝试了我在 stackoverflow 站点中找到的函数,stackoverflow.com/questions/149055/… 但结果是 NaN
  • jquery、keyup、trim :) 这些是让你前进的关键词,因为我认为包括我在内的任何人都不会为完整的答案而烦恼。
  • 这是关于格式化的问题,是关于事件处理的问题吗?你说你尝试了另一个答案。你到底尝试了什么?你有没有做出任何改变以适应你的情况?除了另一个答案的副本之外,您是否尝试过其他任何方法? jQuery 解决方案可以吗,还是需要纯 JavaScript?

标签: javascript onkeyup


【解决方案1】:

这是一个有趣的古怪格式函数:

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

【讨论】:

    【解决方案2】:

    你需要这样的东西:

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

    【讨论】:

      【解决方案3】:
      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;
      

      【讨论】:

      • @whitebox:哎呀。我已经测试了正则表达式,但没有一起测试整个事情。现在应该可以工作了。
      • 不允许.00,允许多个','
      • @BantyRoy:这段代码无意关注.。您可能已经注意到,数字的格式不同。 , 在这种情况下是小数点,通常表示 .是千位分隔符。
      猜你喜欢
      • 2017-07-02
      • 1970-01-01
      • 1970-01-01
      • 2015-08-21
      • 1970-01-01
      • 2016-03-09
      • 1970-01-01
      • 1970-01-01
      • 2019-01-28
      相关资源
      最近更新 更多