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

僤鯓⒐⒋嵵緔 提交于 2019-12-22 05:17:00

问题


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

回答1:


$(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);
});



回答2:


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?



来源:https://stackoverflow.com/questions/4407450/trying-to-format-number-to-2-decimal-places-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!