【问题标题】:Decimal Number Formatting in Input输入中的十进制数字格式
【发布时间】:2012-11-13 03:49:33
【问题描述】:

目前我在格式化小数方面遇到问题。

关于文本框的模糊事件,如果用户输入:

1) 1    -> this should be converted to 001.00
2) 2.5  -> this should be converted to 002.50
3) .5   -> this should be converted to 000.50
4) 12.4 -> this should be converted to 012.40

在离开输入或失去焦点时,所有输入都应转换为相同的格式。

【问题讨论】:

  • 需要更多信息。您希望在输入字段中进行转换吗?在文中?在验证之前在服务器上?您使用的是 jQuery 还是任何其他 JS 框架?干杯
  • 是的,它应该被转换,同时使用纯 Javascript.Thnks 将文本框留在客户端

标签: javascript forms string-formatting number-formatting


【解决方案1】:
<input type="text" onblur="formatDecimal(this)" />

<script type="text/javascript">
    function formatDecimal(input) {
        var val = '' + (+input.value);
        if (val) {
            val = val.split('\.');
            var out = val[0];
            while (out.length < 3) {
                out = '0' + out;
            }
            if (val[1]) {
                out = out + '.' + val[1]
                if (out.length < 6) out = out + '0';
            } else {
                out = out + '.00';
            }
            input.value = out;
        } else {
            input.value = '000.00';
        }
    }
</script>

【讨论】:

  • 感谢 Buddy。它真的有效!!你拯救了我的一天!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-03-30
  • 1970-01-01
  • 2014-12-03
  • 2010-10-14
  • 2016-01-24
  • 2016-04-21
  • 1970-01-01
相关资源
最近更新 更多