Tofixed is not a function ошибка

.toFixed() is only a function of a number and returns a string. By using toFixed in multiple assignments, you’re turning a number into a string, concatenating multiple strings together, then trying to do a numerical operation on a string.

The following code will give an error.

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

If you need to avoid floating-point errors, then convert the string to a number before adding it to another number, for example:

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

Otherwise, wait until you’re done with your calculations to use toFixed to round to the number of decimal places you want to display, for example:

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

Apu

Sometimes, when we use the toFixed() method, we may see the error TypeError: toFixed is not a function. This is because the toFixed() method is called on a value that is not a number.

Solution #

To solve that problem, convert the value to number using the Number() method.

<script>
  const myString = '12.8798';
  const newNumber = Number(myString).toFixed(2);
  console.log(newNumber)
</script>

Here is an example of how this error occurs.

<script>
  const myString = '12.8798';
  console.log(myString.toFixed(2));
</script>

To fix this error, first we can convert the value to a number before calling the toFixed() method.

However, do you know how we can check whether a variable is a number or a string?

That’s easy. we can use the typeof operator to check. Try the below example.


Example : uses of typeof operator. #

<script> 
  const num = '12345';

  console.log("'12345' is a " + typeof num)
  console.log("myVar is a " + typeof myVar)
  console.log("9 is a " + typeof 9)
  console.log(" [5,6,7] is a " + typeof [5,6,7])
</script>

Now come to the topic. To convert a string to a number, we can use the Number() method. E.g.


Example : fix the error toFixed is not a function. #

<script>
 const myString = '12.8798';
 const result = Number(myString).toFixed(2);
 console.log(result)
</script>

Conclusion #

In this article, you have learned how to solve The «toFixed is not a function» error. This error occurs when the toFixed() method is called on a value that is not a number. To solve the error, we must convert the value to a number before calling the toFixed method.

Здесь я пытаюсь добавить два десятичных значения в строку 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>

Перейти к ответу
Данный вопрос помечен как решенный


Ответы
5

Метод toFixed() форматирует номер. Текущее значение имеет тип нить и вместо арифметическое сложение происходит конкатенация строк. Преобразуйте их в номер перед добавлением:

Изменять:

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

К

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

Метод toFixed недоступен для значений non-number. вам нужно сначала проанализировать значение до Число, чем вы можете использовать метод toFixed.

let str = `123.123456`

console.info(Number(str).toFixed(3))
console.error(str.toFixed(3))

Только значение float, int имеют toFixed. контролируйте свою переменную и смотрите, какого они типа.

console.info(("4" + 5).toFixed(3)); // error

console.info((5 + 5).toFixed(3)); // yeep its working

Проверьте тип данных обеих переменных. Они должны быть числовыми, а не строковыми. Метод toFixed не будет работать для других типов данных. Также убедитесь, что когда вы конвертируете строку в число, значение в строке внутренне является числом, например «22», а не «привет», поскольку преобразование его в число может дать вам NaN, и ваша программа может завершиться ошибкой.

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

Другие вопросы по теме

Add Answer
|
View In TPC Matrix

Technical Problem Cluster First Answered On
July 2, 2021

Popularity
10/10

Helpfulness
4/10


Contributions From The Grepper Developer Community

Contents

Code Examples

  • javascript tofixed is not a function
  • Related Problems

  • tofixed is not a function
  • sub_total.toFixed is not a function
  • TPC Matrix View Full Screen

    javascript tofixed is not a function

    Comment

    0


    Popularity

    10/10 Helpfulness
    4/10
    Language
    javascript

    Source: stackoverflow.com

    Tags: function
    javascript
    tofixed

    Singh99

    Contributed on Jul 02 2021

    Singh99

    541 Answers  Avg Quality 6/10


    Здесь я пытаюсь добавить два десятичных значения в строку 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>
    

    4 ответа

    Лучший ответ

    toFixed() форматирует число . Текущее значение имеет тип строка и вместо арифметического сложения , конкатенация строк происходит. Преобразуйте их в номер перед добавлением и использованием toFixed():

    Изменить:

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

    К

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


    2

    Mamun
    17 Фев 2019 в 09:19

    Проверьте тип данных обеих переменных. Они должны быть числовыми, а не строками. Метод toFixed не будет работать для других типов данных. Также убедитесь, что при преобразовании строки в число значение в строке является внутренним числом типа «22», а не «привет», так как преобразование его в число может дать вам NaN, и ваша программа может завершиться ошибкой.


    0

    Sagar Agrawal
    17 Фев 2019 в 12:01

    Только значение с плавающей запятой, значение int имеет toFixed. контролировать вашу переменную и посмотреть, какой тип они.

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


    0

    Alen.Toma
    17 Фев 2019 в 09:02

    toFixed метод недоступен для non-number значений. вам нужно разобрать значение в номер первым, чем вы можете использовать метод toFixed.

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


    1

    Code Maniac
    17 Фев 2019 в 09:02

    The topic of this article is how to fix Uncaught TypeError: num.toFixed is not a function in JavaScript. You can assign a numeric value to a variable or convert the variable to a number to fix this error. Let’s go into detail now.

    This error occurs because the program cannot recognize the function toFixed(), so we need to know what this function does first. The number.toFixed() method converts a number to a string type, retaining the user-defined number of decimal places.

    Syntax:

    number.toFixed(x)

    Parameter:

    • x is the desired number of decimal places.

    Because, like the syntax of this method, the variable used with the toFixed method must be a number, you are passing it a non-numeric value.

    Code:

     const num = "LearnShareIT";
     console.log(num.toFixed());

    Output:

    As you can see, the variable num is assigned a string value and not a number, so the program gives an error that this function cannot be recognized. See the next part of the article to learn how to fix this error.

    How to fix the Uncaught TypeError: num.toFixed is not a function in JavaScript?

    Assign a numeric value to the num variable

    In this way, we replace the value assigned to the variable num with a numeric value, and the program can use the toFixed function. See the code below to understand how it works.

    Code:

     const num = 99.99;
     console.log(num.toFixed(1));

    Output:

    100.0

    So the error no longer appears, you can see that the num value is assigned to 99.99 and use the toFixed() method and pass the value as 1, so the program rounds the variable and trim the decimal part of the number to one unit.

    Convert the variable to a number

    We can also prevent the error from appearing by converting the string value of the num variable to an int using the parseInt() method in Javascript.

    Code:

     const num = "11.11";
     console.log(parseInt(num).toFixed(1));

    Output:

    11.0

    Therefore, we can convert the string value to a numeric value. We can use the toFixed method you need to use.

    Summary

    To sum up, you have been shown two ways to prevent the Uncaught TypeError: num.toFixed is not a function in JavaScript from appearing. However, I recommend assigning a numeric value to the num variable. Good lucks to you!

    Maybe you are interested:

    • TypeError: Cannot read property ‘getAttribute’ of Null in JavaScript
    • TypeError: Assignment to Constant Variable in JavaScript
    • TypeError: contains is not a function in JavaScript

    Nathaniel Kirk

    Hi, my name’s Nathaniel Kirk. I’m interested in learning and sharing knowledge about programming languages. My strengths are C, C++, Python, HTML, CSS, Javascript, and Reactjs. If you have difficulty with them, don’t worry. I’m here to support you.


    Name of the university: PTIT
    Major: IT
    Programming Languages: C, C++, Python, HTML, CSS, Javascript, Reactjs

    Здесь я пытаюсь добавить два десятичных значения в строку 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>
    

    Перейти к ответу
    Данный вопрос помечен как решенный


    Ответы
    5

    Метод toFixed() форматирует номер. Текущее значение имеет тип нить и вместо арифметическое сложение происходит конкатенация строк. Преобразуйте их в номер перед добавлением:

    Изменять:

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

    К

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

    Метод toFixed недоступен для значений non-number. вам нужно сначала проанализировать значение до Число, чем вы можете использовать метод toFixed.

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

    Только значение float, int имеют toFixed. контролируйте свою переменную и смотрите, какого они типа.

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

    Проверьте тип данных обеих переменных. Они должны быть числовыми, а не строковыми. Метод toFixed не будет работать для других типов данных. Также убедитесь, что когда вы конвертируете строку в число, значение в строке внутренне является числом, например «22», а не «привет», поскольку преобразование его в число может дать вам NaN, и ваша программа может завершиться ошибкой.

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

    Другие вопросы по теме

    Здесь я пытаюсь добавить два десятичных значения в строку 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>
    

    4 ответа

    Лучший ответ

    toFixed() форматирует число . Текущее значение имеет тип строка и вместо арифметического сложения , конкатенация строк происходит. Преобразуйте их в номер перед добавлением и использованием toFixed():

    Изменить:

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

    К

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


    2

    Mamun
    17 Фев 2019 в 09:19

    Проверьте тип данных обеих переменных. Они должны быть числовыми, а не строками. Метод toFixed не будет работать для других типов данных. Также убедитесь, что при преобразовании строки в число значение в строке является внутренним числом типа «22», а не «привет», так как преобразование его в число может дать вам NaN, и ваша программа может завершиться ошибкой.


    0

    Sagar Agrawal
    17 Фев 2019 в 12:01

    Только значение с плавающей запятой, значение int имеет toFixed. контролировать вашу переменную и посмотреть, какой тип они.

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


    0

    Alen.Toma
    17 Фев 2019 в 09:02

    toFixed метод недоступен для non-number значений. вам нужно разобрать значение в номер первым, чем вы можете использовать метод toFixed.

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


    1

    Code Maniac
    17 Фев 2019 в 09:02

    • I’ve looked at the documentation to make sure the behaviour is documented and expected
    • I’m sure this is a Leaflet Draw code issue, not an issue with my own code nor with the framework I’m using (Cordova, Ionic, Angular, React…)
      -I’ve searched through the issues to make sure it’s not yet reported

    How to reproduce

    • Leaflet version I’m using: 1.0
    • Leaflet Draw version I’m using: Latest
    • Browser (with version) I’m using: Chrome
    • OS/Platform (with version) I’m using: Windows 10

    Hi,
    Using the example, when I start drawing a circle object, I get this following error.

    GeometryUtil.js:45 Uncaught TypeError: n.toFixed is not a function
    at Object.formattedNumber (GeometryUtil.js:45)
    at Object.readableDistance (GeometryUtil.js:130)
    at NewClass._onMouseMove (Draw.Circle.js:68)
    at NewClass.fire (Events.js:186)
    at NewClass._touchEvent (TouchEvents.js:78)
    at NewClass._onTouchMove (TouchEvents.js:151)
    at handler (DomEvent.js:72)
    at Object._handlePointer (DomEvent.Pointer.js:107)
    at Object. (DomEvent.Pointer.js:115)

    A closure is a pairing of:

    1. A function, and
    2. A reference to that function’s outer scope (lexical environment)

    A lexical environment is part of every execution context (stack frame) and is a map between identifiers (ie. local variable names) and values.

    Every function in JavaScript maintains a reference to its outer lexical environment. This reference is used to configure the execution context created when a function is invoked. This reference enables code inside the function to «see» variables declared outside the function, regardless of when and where the function is called.

    If a function was called by a function, which in turn was called by another function, then a chain of references to outer lexical environments is created. This chain is called the scope chain.

    In the following code, inner forms a closure with the lexical environment of the execution context created when foo is invoked, closing over variable secret:

    function foo() {
      const secret = Math.trunc(Math.random()*100)
      return function inner() {
        console.log(`The secret number is ${secret}.`)
      }
    }
    const f = foo() // `secret` is not directly accessible from outside `foo`
    f() // The only way to retrieve `secret`, is to invoke `f`

    In other words: in JavaScript, functions carry a reference to a private «box of state», to which only they (and any other functions declared within the same lexical environment) have access. This box of the state is invisible to the caller of the function, delivering an excellent mechanism for data-hiding and encapsulation.

    And remember: functions in JavaScript can be passed around like variables (first-class functions), meaning these pairings of functionality and state can be passed around your program: similar to how you might pass an instance of a class around in C++.

    If JavaScript did not have closures, then more states would have to be passed between functions explicitly, making parameter lists longer and code noisier.

    So, if you want a function to always have access to a private piece of state, you can use a closure.

    …and frequently we do want to associate the state with a function. For example, in Java or C++, when you add a private instance variable and a method to a class, you are associating state with functionality.

    In C and most other common languages, after a function returns, all the local variables are no longer accessible because the stack-frame is destroyed. In JavaScript, if you declare a function within another function, then the local variables of the outer function can remain accessible after returning from it. In this way, in the code above, secret remains available to the function object inner, after it has been returned from foo.

    Uses of Closures

    Closures are useful whenever you need a private state associated with a function. This is a very common scenario — and remember: JavaScript did not have a class syntax until 2015, and it still does not have a private field syntax. Closures meet this need.

    Private Instance Variables

    In the following code, the function toString closes over the details of the car.

    function Car(manufacturer, model, year, color) {
      return {
        toString() {
          return `${manufacturer} ${model} (${year}, ${color})`
        }
      }
    }
    const car = new Car('Aston Martin','V8 Vantage','2012','Quantum Silver')
    console.log(car.toString())

    Functional Programming

    In the following code, the function inner closes over both fn and args.

    function curry(fn) {
      const args = []
      return function inner(arg) {
        if(args.length === fn.length) return fn(...args)
        args.push(arg)
        return inner
      }
    }
    
    function add(a, b) {
      return a + b
    }
    
    const curriedAdd = curry(add)
    console.log(curriedAdd(2)(3)()) // 5

    Event-Oriented Programming

    In the following code, function onClick closes over variable BACKGROUND_COLOR.

    const $ = document.querySelector.bind(document)
    const BACKGROUND_COLOR = 'rgba(200,200,242,1)'
    
    function onClick() {
      $('body').style.background = BACKGROUND_COLOR
    }
    
    $('button').addEventListener('click', onClick)
    <button>Set background color</button>

    Modularization

    In the following example, all the implementation details are hidden inside an immediately executed function expression. The functions tick and toString close over the private state and functions they need to complete their work. Closures have enabled us to modularise and encapsulate our code.

    let namespace = {};
    
    (function foo(n) {
      let numbers = []
      function format(n) {
        return Math.trunc(n)
      }
      function tick() {
        numbers.push(Math.random() * 100)
      }
      function toString() {
        return numbers.map(format)
      }
      n.counter = {
        tick,
        toString
      }
    }(namespace))
    
    const counter = namespace.counter
    counter.tick()
    counter.tick()
    console.log(counter.toString())

    Examples

    Example 1

    This example shows that the local variables are not copied in the closure: the closure maintains a reference to the original variables themselves. It is as though the stack-frame stays alive in memory even after the outer function exits.

    function foo() {
      let x = 42
      let inner  = function() { console.log(x) }
      x = x+1
      return inner
    }
    var f = foo()
    f() // logs 43

    Example 2

    In the following code, three methods log, increment, and update all close over the same lexical environment.

    And every time createObject is called, a new execution context (stack frame) is created and a completely new variable x, and a new set of functions (log etc.) are created, that close over this new variable.

    function createObject() {
      let x = 42;
      return {
        log() { console.log(x) },
        increment() { x++ },
        update(value) { x = value }
      }
    }
    
    const o = createObject()
    o.increment()
    o.log() // 43
    o.update(5)
    o.log() // 5
    const p = createObject()
    p.log() // 42

    Example 3

    If you are using variables declared using var, be careful you understand which variable you are closing over. Variables declared using var are hoisted. This is much less of a problem in modern JavaScript due to the introduction of let and const.

    In the following code, each time around the loop, a new function inner is created, which closes over i. But because var i is hoisted outside the loop, all of these inner functions close over the same variable, meaning that the final value of i (3) is printed, three times.

    function foo() {
      var result = []
      for (var i = 0; i < 3; i++) {
        result.push(function inner() { console.log(i) } )
      }
      return result
    }
    
    const result = foo()
    // The following will print `3`, three times...
    for (var i = 0; i < 3; i++) {
      result[i]() 
    }

    Final points:

    • Whenever a function is declared in JavaScript closure is created.
    • Returning a function from inside another function is the classic example of closure, because the state inside the outer function is implicitly available to the returned inner function, even after the outer function has completed execution.
    • Whenever you use eval() inside a function, a closure is used. The text you eval can reference local variables of the function, and in the non-strict mode, you can even create new local variables by using eval('var foo = …').
    • When you use new Function(…) (the Function constructor) inside a function, it does not close over its lexical environment: it closes over the global context instead. The new function cannot reference the local variables of the outer function.
    • A closure in JavaScript is like keeping a reference (NOT a copy) to the scope at the point of function declaration, which in turn keeps a reference to its outer scope, and so on, all the way to the global object at the top of the scope chain.
    • A closure is created when a function is declared; this closure is used to configure the execution context when the function is invoked.
    • A new set of local variables is created every time a function is called.

    Links

    • Douglas Crockford’s simulated private attributes and private methods for an object, using closures.
    • A great explanation of how closures can cause memory leaks in IE if you are not careful.
    • MDN documentation on JavaScript Closures.

    Native deep cloning

    It’s called «structured cloning», works experimentally in Node 11 and later, and hopefully will land in browsers. See this answer for more details.

    Fast cloning with data loss — JSON.parse/stringify

    If you do not use Dates, functions, undefined, Infinity, RegExps, Maps, Sets, Blobs, FileLists, ImageDatas, sparse Arrays, Typed Arrays or other complex types within your object, a very simple one liner to deep clone an object is:

    JSON.parse(JSON.stringify(object))

    const a = {
      string: 'string',
      number: 123,
      bool: false,
      nul: null,
      date: new Date(),  // stringified
      undef: undefined,  // lost
      inf: Infinity,  // forced to 'null'
      re: /.*/,  // lost
    }
    console.log(a);
    console.log(typeof a.date);  // Date object
    const clone = JSON.parse(JSON.stringify(a));
    console.log(clone);
    console.log(typeof clone.date);  // result of .toISOString()

    See Corban’s answer for benchmarks.

    Reliable cloning using a library

    Since cloning objects is not trivial (complex types, circular references, function etc.), most major libraries provide function to clone objects. Don’t reinvent the wheel — if you’re already using a library, check if it has an object cloning function. For example,

    • lodash — cloneDeep; can be imported separately via the lodash.clonedeep module and is probably your best choice if you’re not already using a library that provides a deep cloning function
    • AngularJS — angular.copy
    • jQuery — jQuery.extend(true, { }, oldObject); .clone() only clones DOM elements
    • just library — just-clone; Part of a library of zero-dependency npm modules that do just do one thing.
      Guilt-free utilities for every occasion.

    ES6 (shallow copy)

    For completeness, note that ES6 offers two shallow copy mechanisms: Object.assign() and the spread syntax.
    which copies values of all enumerable own properties from one object to another. For example:

    var A1 = {a: "2"};
    var A2 = Object.assign({}, A1);
    var A3 = {...A1};  // Spread Syntax
    

    Понравилась статья? Поделить с друзьями:
  • Tocaedit xbox 360 controller emulator ошибка
  • To speak in english ошибка
  • Tnt premier неизвестная ошибка
  • Tns 03505 ошибка
  • Tnpa5330 ошибка 6