在jQuery中,将数字格式化为2位小数的最佳方法是什么?
问题描述:
这就是我现在所拥有的:
This is what I have right now:
$("#number").val(parseFloat($("#number").val()).toFixed(2));
对我而言看起来很麻烦。我认为我没有正确地链接这些功能。我是否必须为每个文本框调用它,或者我可以创建一个单独的函数吗?
It looks messy to me. I don't think I'm chaining the functions correctly. Do I have to call it for each textbox, or can I create a separate function?
答
如果你这样做的话几个字段,或经常这样做,然后也许一个插件就是答案。
这是一个jQuery插件的开头,它将字段的值格式化为两位小数。
它由字段的onchange事件触发。你可能想要不同的东西。
If you're doing this to several fields, or doing it quite often, then perhaps a plugin is the answer.
Here's the beginnings of a jQuery plugin that formats the value of a field to two decimal places.
It is triggered by the onchange event of the field. You may want something different.
<script type="text/javascript">
// mini jQuery plugin that formats to two decimal places
(function($) {
$.fn.currencyFormat = function() {
this.each( function( i ) {
$(this).change( function( e ){
if( isNaN( parseFloat( this.value ) ) ) return;
this.value = parseFloat(this.value).toFixed(2);
});
});
return this; //for chaining
}
})( jQuery );
// apply the currencyFormat behaviour to elements with 'currency' as their class
$( function() {
$('.currency').currencyFormat();
});
</script>
<input type="text" name="one" class="currency"><br>
<input type="text" name="two" class="currency">