Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 697
Iain Holder Avatar asked Jan 25 '09 16:01

Iain Holder


People also ask

How do I get 2 decimal places in jQuery?

$("#diskamountUnit"). val('$' + $("#disk"). slider("value") * 1.60);

How do you move a number to 2 decimal places?

Rounding a decimal number to two decimal places is the same as rounding it to the hundredths place, which is the second place to the right of the decimal point. For example, 2.83620364 can be round to two decimal places as 2.84, and 0.7035 can be round to two decimal places as 0.70.

What is the number 2.738 correct to 2 decimal places?

74, which is 2 decimal places.

How do you round a number to 2 decimal places in JavaScript?

Use the toFixed() method to round a number to 2 decimal places, e.g. const result = num. toFixed(2) . The toFixed method will round and format the number to 2 decimal places.


2 Answers

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"> 
like image 52
meouw Avatar answered Sep 26 '22 12:09

meouw


Maybe something like this, where you could select more than one element if you'd like?

$("#number").each(function(){     $(this).val(parseFloat($(this).val()).toFixed(2)); }); 
like image 43
Svante Svenson Avatar answered Sep 23 '22 12:09

Svante Svenson