Javascript 在jQuery中,什么';将数字格式化为小数点后2位的最佳方法是什么?
这就是我现在拥有的:Javascript 在jQuery中,什么';将数字格式化为小数点后2位的最佳方法是什么?,javascript,jquery,rounding,decimal-point,number-formatting,Javascript,Jquery,Rounding,Decimal Point,Number Formatting,这就是我现在拥有的: $("#number").val(parseFloat($("#number").val()).toFixed(2)); 在我看来它很乱。我认为我没有正确地链接函数。我必须为每个文本框调用它吗,或者我可以创建一个单独的函数吗?可能类似于这样,如果您愿意,您可以选择多个元素 $(“#编号”)。每个(函数(){ $(this.val)(parseFloat($(this.val()).toFixed(2)); }); 如果您正在对多个字段执行此操作,或者经常执行此操作,那么也
$("#number").val(parseFloat($("#number").val()).toFixed(2));
在我看来它很乱。我认为我没有正确地链接函数。我必须为每个文本框调用它吗,或者我可以创建一个单独的函数吗?可能类似于这样,如果您愿意,您可以选择多个元素
$(“#编号”)。每个(函数(){
$(this.val)(parseFloat($(this.val()).toFixed(2));
});
如果您正在对多个字段执行此操作,或者经常执行此操作,那么也许插件就是答案。以下是jQuery插件的开始,该插件将字段的值格式化为小数点后两位。
它由字段的onchange事件触发。你可能想要一些不同的东西
<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">
//迷你jQuery插件,格式为两位小数
(函数($){
$.fn.currencyFormat=函数(){
这是每个功能(i){
$(此).更改(功能(e){
if(isNaN(parseFloat(this.value)))返回;
this.value=parseFloat(this.value).toFixed(2);
});
});
返回此;//用于链接
}
})(jQuery);
//将currencyFormat行为应用于类为“currency”的元素
$(函数(){
$('.currency').currencyFormat();
});
我们修改了一个Meouw函数,以便与keyup一起使用,因为当您使用输入时,它会更有帮助
选中此项:
嘿,那里@heridev和我在jQuery中创建了一个小函数
您可以尝试下一步:
HTML
在线演示:
(@heridev,@vicmaster)另一方面,您的dom中不应该有重复的ID。考虑将“数字”改为一个类。@ GraveBoT——这并不意味着ID=“数字”有不止一个元素。看起来svinto只是使用“each”函数来减少神奇字符串“#number”在代码中出现的次数。这是对Lainmm代码的一个小小的(我认为是很好的)改进。如果这种格式化只需要在一个页面上完成,那么这就是我更喜欢的方式。如果需要在多个页面上复制,然后我更喜欢meouw的插件方法-除了提取到外部javascript文件。@DanielSchilling..我想gradbot想说的是,如果你想在一个页面上的多个输入框上应用相同的函数,那么你也不能向它们提供相同的id,或者你不能像这样继续提到每个输入框的id
('#num1,#num2')。每个(函数(){})所以最好像这样使用类方法('.number')。每个(函数(){})代码>。并为每个输入框提供一个公共类-numberHi,我想知道我们是否需要另一个插件来currencyFormat()?…我想您可能希望使用.change()代替.keyup()。。。
<input type="text" name="one" class="two-digits"><br>
<input type="text" name="two" class="two-digits">
// apply the two-digits behaviour to elements with 'two-digits' as their class
$( function() {
$('.two-digits').keyup(function(){
if($(this).val().indexOf('.')!=-1){
if($(this).val().split(".")[1].length > 2){
if( isNaN( parseFloat( this.value ) ) ) return;
this.value = parseFloat(this.value).toFixed(2);
}
}
return this; //for chaining
});
});