In jQuery, what's the best way of formatting a number to 2 decimal places?
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?
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">
也许像这样,如果你愿意,你可以选择多个元素?
$("#number").each(function(){
$(this).val(parseFloat($(this).val()).toFixed(2));
});
We modify a Meouw function to be used with keyup, because when you are using an input it can be more helpful.
Check this:
Hey there!, @heridev and I created a small function in jQuery.
You can try next:
HTML
<input type="text" name="one" class="two-digits"><br>
<input type="text" name="two" class="two-digits">
jQuery
// 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
});
});
DEMO ONLINE:
http://jsfiddle.net/c4Wqn/
(@heridev, @vicmaster)
链接地址: http://www.djcxy.com/p/77454.html上一篇: 从数字中删除无用的尾随零?