Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to format number to 2 decimal places jQuery [duplicate]

Possible Duplicate:
JavaScript: formatting number with exactly two decimals

Getting a bit muddled up using variables and now cant seem to get calculation to work at all!?

 $("#discount").change(function(){
            var list = $("#list").val();
            var discount = $("#discount").val();
            var price = $("#price");
            var temp = discount * list;
            var temp1 = list - temp;
            var total = parseFloat($(this).temp1()).toFixed(2);

            price.val(total);       
 });
like image 548
benhowdle89 Avatar asked Dec 10 '10 09:12

benhowdle89


People also ask

How do I fix two decimal places in jQuery?

To limit the number of digits up to 2 places after the decimal, the toFixed() method is used. The toFixed() method rounds up the floating-point number up to 2 places after the decimal.

How do you make a double show with two decimal places?

Just use %. 2f as the format specifier. This will make the Java printf format a double to two decimal places. /* Code example to print a double to two decimal places with Java printf */ System.

How do you round a double value 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.

How do I display a decimal value to 2 decimal places?

decimalVar. ToString("F"); This will: Round off to 2 decimal places eg.


2 Answers

$(this).temp1() looks particularly out of place, I think you just meant to use the temp1 variable. Since it's already a number, you don't need to use parseFloat on it either:

$("#discount").change(function() {
    var list = $("#list").val();
    var discount = $("#discount").val();
    var price = $("#price");
    var temp = discount * list;
    var temp1 = list - temp;
    var total = temp1.toFixed(2);

    price.val(total);
});
like image 155
Andy E Avatar answered Sep 18 '22 16:09

Andy E


I would suggest you to convert strings to number first before calculation. For example,

var list = parseFloat($("#list").val());
var discount = parseFloat($("#discount").val());
var price = $("#price");
var total = list - (discount * list);
price.val(total.toFixed(2));

Also, if discount is in percentage (for example, say 25) then you have to divide by 100 i.e. list - (discount/100 * list)

BTW, refer this SO thread where people had warned against ToFixed usage: How to format a float in javascript?

like image 41
VinayC Avatar answered Sep 22 '22 16:09

VinayC