【问题标题】:How to fix javascript .toFixed is not a Function error如何修复 javascript .toFixed 不是函数错误
【发布时间】:2019-07-10 21:51:52
【问题描述】:

在这里,我试图在var totalSum = (grandTotal + getShippingCost).toFixed(3); 行中添加两个十进制值,并将值放入var getSumTd = $("tr#sumTr").find("span#sumSpan");

但问题是var totalSum = (grandTotal + getShippingCost).toFixed(3); 会抛出一个错误,说Uncaught TypeError: value.toFixed is not a function

对我的代码有任何帮助都会有很大帮助。

以下是我的脚本

<script>
$('button#value-plus').on('click', function () {
    debugger;
    var divUpd = $(this).closest("tr").find('#qnty');
    var subtotalcontainer = $(this).closest("tr").find('span#subtotal');
    var mainGrandTotalcontainer = $("tr#mainGtTr").find("#mainGt");
    var mainGtVal = parseFloat($("tr#mainGtTr").find('span#shippingCost').text());

    var getSumTd = $("tr#sumTr").find("span#sumSpan");
    var getShippingCost = parseFloat($("tr#mainGtTr").find('span#mainGt1').text());

    var bklId = $(this).closest("tr").find('#pid').val();
    var url = "/Product/incrementcart";
    $.getJSON(url, { prdid: bklId }, function (data) {
        debugger;
        divUpd.val(data.qty);
        var subTotal = data.qty * data.price;
        subtotalcontainer.text(subTotal.toFixed(2));

        var grandTotal = (mainGtVal + data.price).toFixed(3);
        mainGrandTotalcontainer.text(grandTotal);

        var totalSum = (grandTotal + getShippingCost).toFixed(3);
        getSumTd.text(totalSum);

    }).success(function () {
        debugger
        var url = "/Product/cartupdate";
        $.get(url, function (data) {
            debugger;
            $(".shopping_button").html(data);
        })
    });
});   



下面是我的 HTML

     <tbody>
                        @foreach (var item in Model)
                        {
                            <tr>
                                @Html.HiddenFor(model => item.ProductId, htmlAttributes: new { @id = "pid" })
                                <td data-title="Product Image &amp; name" class="t_md_align_c">
                                    <img src="images/quick_view_img_10.jpg" alt="" class="m_md_bottom_5 d_xs_block d_xs_centered">
                                    <a href="#" class="d_inline_b m_left_5 color_dark">@Html.DisplayFor(modelItem => item.ProductName)</a>
                                </td>
                                <td data-title="Stock">
                                    @Html.DisplayFor(modelItem => item.Instock)
                                </td>
                                <td data-title="Price">
                                    <p class="f_size_large color_dark">$@Html.DisplayFor(modelItem => item.ProductPrice)</p>
                                </td>
                                <td data-title="Quantity">
                                    <div class="clearfix quantity r_corners d_inline_middle f_size_medium color_dark m_bottom_10">
                                        <button class="bg_tr d_block f_left" data-direction="down" id="value-minus">-</button>
                                        <input type="text" name="" id="qnty" readonly value="@item.Quantity" class="f_left">
                                        <button class="bg_tr d_block f_left" data-direction="up" id="value-plus">+</button>
                                    </div>
                                </td>
                                <td data-title="Subtotal">
                                    <p class="f_size_large fw_medium scheme_color">$<span id="subtotal">@Html.DisplayFor(modelItem => item.Total)</span></p>
                                </td>
                                <td data-title="Remove">
                                    <a href="#" class="color_dark"><i class="fa fa-times f_size_medium m_right_5"></i>Remove</a><br>
                                </td>
                            </tr>
                        }
                        <tr id="mainGtTr">
                            <td colspan="4" class="v_align_m d_ib_offset_large t_xs_align_l">
                                <div class="d_ib_offset_0 d_inline_middle half_column d_xs_block w_xs_full m_xs_bottom_5">
                                    <button class="button_type_6 bg_scheme_color f_size_large r_corners tr_all_hover color_light m_bottom_20">Check Out </button>
                                </div>
                                <p class="fw_medium f_size_large t_align_r scheme_color p_xs_hr_0 d_inline_middle half_column d_ib_offset_normal d_xs_block w_xs_full t_xs_align_c">Grand Total:</p>
                            </td>
                            <td colspan="2" class="v_align_m">
                                <p class="fw_medium f_size_large scheme_color m_xs_bottom_10">$<span id="mainGt">@ViewBag.SubTotal</span></p>
                                <p style="font-style:oblique">Include <i class="fa fa-rupee"></i> <span id="shippingCost">@ViewBag.ShipingCost</span> shipping cost</p>
                            </td>
                        </tr>
                        @{
                            var sum = ViewBag.SubTotal + ViewBag.ShipingCost;
                        }
                        <tr id="sumTr">
                            <td>
                                <span id="sumSpan">@sum</span>
                            </td>
                        </tr>
                    </tbody>

【问题讨论】:

  • grandTotal 是一个字符串,因为它是从toFixed 构造的,而字符串没有toFixed 方法

标签: javascript c# jquery asp.net-mvc


【解决方案1】:

toFixed() 方法格式化一个数字。当前值为 string 类型,而不是 算术加法字符串连接 正在发生。在添加之前将它们转换为数字

变化:

var totalSum = (grandTotal + getShippingCost).toFixed(3);

var totalSum = (Number(grandTotal) + Number(getShippingCost)).toFixed(3);

【讨论】:

    【解决方案2】:

    .toFixed() 只是一个数字的函数并返回一个字符串。通过在多个赋值中使用 toFixed,您可以将数字转换为字符串,将多个字符串连接在一起,然后尝试对字符串进行数字运算。

    下面的代码会报错。

    var grandTotal = (mainGtVal + data.price).toFixed(3); // grandTotal is a string
    var totalSum = (grandTotal + getShippingCost).toFixed(3); // grandTotal + getShippingCost is a String, which doesn't have the toFixed function
    

    如果需要避免浮点错误,那么先将字符串转换为数字,然后再添加到另一个数字,例如:

    var grandTotal = (mainGtVal + data.price).toFixed(3);
    grandTotal = Number.parseFloat(grandTotal);
    var totalSum = (grandTotal + getShippingCost).toFixed(3);
    

    否则,请等到完成计算后再使用 toFixed 舍入到要显示的小数位数,例如:

    var grandTotal = mainGtVal + data.price;
    var totalSum = (grandTotal + getShippingCost).toFixed(3);
    grandTotal = grandTotal.toFixed(3);
    

    【讨论】:

      【解决方案3】:

      检查两个变量的数据类型。它们应该是数字而不是字符串。 toFixed 方法不适用于其他数据类型。还要确保当您将字符串转换为数字时,字符串中的值在内部是一个数字,例如“22”而不是“hello”,因为将其转换为数字可能会给您 NaN 并且您的程序可能会失败。

      【讨论】:

        【解决方案4】:

        toFixed 方法不适用于 non-number 值。您需要先将值解析为Number,然后才能使用toFixed 方法。

        let str = `123.123456`
        
        console.log(Number(str).toFixed(3))
        console.error(str.toFixed(3))

        【讨论】:

          【解决方案5】:

          只有浮点数、整数值有toFixed。控制你的变量,看看它们是什么类型。

          console.log(("4" + 5).toFixed(3)); // error
          
          console.log((5 + 5).toFixed(3)); // yeep its working

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2019-12-25
            • 1970-01-01
            • 1970-01-01
            • 2021-06-12
            • 2019-07-01
            • 1970-01-01
            • 1970-01-01
            • 2021-12-01
            相关资源
            最近更新 更多