【问题标题】:jQuery math returns 0.0 but 0.00 is requiredjQuery 数学返回 0.0 但需要 0.00
【发布时间】:2023-03-04 02:55:01
【问题描述】:

我有以下功能:

function checktotal(){
    total = currentproduct["priceperticket"] * $("#qtyselect").val();
    $("span#totalprice").html("$"+total);
}

当它的总数为 65.50 时,它返回 65.5。

不知道是不是需要在.做一个length或者split然后加入一个0或者怎么办。

【问题讨论】:

    标签: jquery math numbers dollar-sign


    【解决方案1】:

    【讨论】:

    • 使用内置的.toFixed() 函数是一个更好的解决方案。
    【解决方案2】:

    使用'toFixed'方法:

    $("span#totalprice").html("$"+total.toFixed(2));
    

    【讨论】:

      【解决方案3】:

      尝试使用.toFixed(2)。见下文,

      function checktotal(){
          total = parseFloat(currentproduct["priceperticket"] * $("#qtyselect").val()).toFixed(2);
          $("span#totalprice").html("$"+total);
      }
      

      【讨论】:

        【解决方案4】:

        根据您项目的性质,您可能需要考虑使用accounting.js

        实现目标的一种简单方法是使用 .toFixed() 函数,该函数将使用 2 个小数位呈现数字,但您还应该在进行算术运算之前检查 NaN 值。

        function checktotal(){
            var price = parseFloat(currentproduct["priceperticket"]);
            var quantity = parseFloat($("#qtyselect").val());
        
            // Check if price or quantity is not a number
            // IF so, clear the price display (or do something else)
            if (isNaN(price) || isNaN(quantity))
              $("span#totalprice").html("");
        
            var total = (price * quantity).toFixed(2);
            $("span#totalprice").html("$" + total);
        }
        

        【讨论】:

          【解决方案5】:

          请检查一下

             parseFloat("65.5").toFixed(2)
          

          【讨论】:

            猜你喜欢
            • 2011-06-02
            • 2013-04-03
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-05-16
            • 1970-01-01
            相关资源
            最近更新 更多