jQuery limit to 2 decimal places

Jquery

Jquery Problem Overview


> 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.

Jquery Solutions


Solution 1 - Jquery

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));

Solution 2 - Jquery

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;
};
ā€‹

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMichael PasqualoneView Question on Stackoverflow
Solution 1 - JqueryChristian C. SalvadóView Answer on Stackoverflow
Solution 2 - JqueryRob VandersView Answer on Stackoverflow