在jQuery中,将数字格式化为2位小数的最佳方法是什么? [英] In jQuery, what's the best way of formatting a number to 2 decimal places?

查看:270
本文介绍了在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">

这篇关于在jQuery中,将数字格式化为2位小数的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆