我想在 keyup javascript 事件上格式化金额。我需要这样的结果:
- 100 > 100
- 1000 > 1 000
- 100000000 > 100 000 000
- 1000,12 > 1 000,12
你能帮我吗?
我想在 keyup javascript 事件上格式化金额。我需要这样的结果:
你能帮我吗?
这是一个奇怪的格式函数,想想很有趣:
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.
}
element.addEventListener(...)
您可以使用纯 JavaScript 或 jQuery 中的函数将其附加到元素的“keyup”事件.on(...)
,例如:
$('.my-input').on('keyup', function() {
var $this = $(this);
$this.val(formatNumber($this.val());
});
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;
你需要这样的东西:
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);
};