67

Possible Duplicate:
JavaScript: formatting number with exactly two decimals

How do I limit the following jQuery return to 2 decimal places?

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

I figure I've got to throw toFixed(2) somewhere into there, but I can't seem to get the ordering right or something.

Community
  • 1
  • 1
Michael Pasqualone
  • 2,027
  • 2
  • 15
  • 23

2 Answers2

159

You could use a variable to make the calculation and use toFixed when you set the #diskamountUnit element value:

var amount = $("#disk").slider("value") * 1.60;
$("#diskamountUnit").val('$' + amount.toFixed(2));

You can also do that in one step, in the val method call but IMO the first way is more readable:

$("#diskamountUnit").val('$' + ($("#disk").slider("value") * 1.60).toFixed(2));
Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
  • 1
    lol!... you both understood each other well... and here I am puzzled what's `toFixed()` was.... haha! – Reigel Gallarde Jun 11 '10 at 05:04
  • 1
    @Reigel: lol, [`toFixed`](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Number/toFixed) is a method available for `Number` objects and values that returns a string containing the number represented in *fixed-point notation*, for example: `1.2345.toFixed(2); //--> "1.23"`, so the OP wants to display this formatted number to represent a currency amount `'$' + amount.toFixed(2)` --> `"$1.23"` ;) – Christian C. Salvadó Jun 11 '10 at 05:09
  • cool!... I'm such a noob... my first real work in JS was with jQuery already... so there are more stuff I don't know about JS, that is not mostly use in jQuery... thanks! – Reigel Gallarde Jun 11 '10 at 05:14
16

Here is a working example in both Javascript and jQuery:

http://jsfiddle.net/GuLYN/312/

//In jQuery
$("#calculate").click(function() {
    var num = parseFloat($("#textbox").val());
    var new_num = $("#textbox").val(num.toFixed(2));
});


// In javascript
document.getElementById('calculate').onclick = function() {
    var num = parseFloat(document.getElementById('textbox').value);
    var new_num = num.toFixed(2);
    document.getElementById('textbox').value = new_num;
};
​
Progrower
  • 363
  • 5
  • 18
Rob Vanders
  • 505
  • 1
  • 5
  • 13