2

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

在文本框的 blur 事件上,如果用户输入:

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

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

4

1 回答 1

2
<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>
于 2012-11-25T14:32:55.577 回答