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.

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

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

Describe the bug
Using strings for height and width in the options object generates an error:

                responseDoc
                    .svg(svgRef.current, {
                        height: '18',
                        width: '80',
                    })
Uncaught (in promise) TypeError: t.toFixed is not a function
    roundToPrecision jspdf.es.min.js:86
    hpf jspdf.es.min.js:86
    rect jspdf.es.min.js:86
    render svg2pdf.es.min.js:41
    ...

Now that I know the problem the error is obvious (toFixed on a string throws an error), but I actually thought it was a problem with my SVG React element, so went through every possible combination of trying to get that working before considering that something so simple as my options were wrong.

What version are you using (exact version of svg2pdf.js and jspdf — the yWorks fork version, of course)?
jspdf: 2.5.1
svg2pdf.js: v2.2.1

To Reproduce
Steps to reproduce the behavior:

  1. With the following SVG and JavaScript code
import React, { useRef } from 'react'
import { jsPDF } from 'jspdf'
import 'svg2pdf.js'

const HelloPdf = () => {
  const certificateTemplateRef = useRef(null)
  const svgRef = useRef(null)
  const generatePdf = () => {
    const doc = new jsPDF({ format: 'a4', unit: 'px' })
    doc.html(certificateTemplateRef.current, {
      async callback(responseDoc) {
        // save the document as a PDF with name of Memes
        responseDoc
          .svg(svgRef.current, {
            height: '18',
            width: '80'
          })
          .then(() => {
            responseDoc.save('svgPDF')
          })
      }
    })
  }
  return (
    <div
      style={{
        display: 'flex',
        alignItems: 'center',
        flexDirection: 'column'
      }}
    >
      <button type="button" onClick={generatePdf}>
        PDF
      </button>
      <div ref={certificateTemplateRef}>
        <div>
          <p>Some text</p>
        </div>
      </div>
      <div>
        <svg
          xmlns="http://www.w3.org/2000/svg"
          viewBox="0 0 300 150"
          ref={svgRef}
        >
          <text x="20" y="20">
            Hello, world!
          </text>
        </svg>
      </div>
    </div>
  )
}
export default HelloPdf
  1. I get this result
  2. Or see this error
Uncaught (in promise) TypeError: t.toFixed is not a function
    roundToPrecision jspdf.es.min.js:86
    hpf jspdf.es.min.js:86
    rect jspdf.es.min.js:86
    render svg2pdf.es.min.js:41
    ...

More specifically that breaks here in the minified code:

...throw new Error("Invalid argument passed to jsPDF.roundToPrecision");return t.toFixed(n).replace(/0+$/,"")...

So it’s actually an error that is thrown from jsPDF: https://github.com/parallax/jsPDF/blob/2d9a91916471f1fbe465dbcdc05db0cf22d720ec/src/jspdf.js#L496

Expected behavior
I would have liked it to just work, I’m using Javascript which is usually forgiving if you use the wrong type. I did look at the types.d.ts, but I wasn’t really considering that my options were of the wrong type.

Given that the number type of the options is strict, could you perhaps include in the README documentation that the options must be numbers. Currently you just have:

doc
  .svg(element, {
    x,
    y,
    width,
    height
  })

which gives no indication that the types are strict.

Adding something like the regular jsPDF documentation of doc.html would be very helpful:

svg(element, options) → Promise<jsPDF>

Example
...
Parameters
Name Type Attributes Description
element HTMLElement   The source svg HTMLElement.
options Object <optional>
Name Type Attributes Description
x number <optional> The horizontal offset at which the SVG shall be rendered. The default is 0.
y number <optional> The vertical offset at which the SVG shall be rendered. The default is 0.
width number <optional> The desired width of the rendered SVG. Defines the initial viewport for the outermost SVG element. The width and height properties behave exactly like the width and height attributes on an HTML img element with an SVG image as source.
height number <optional> The desired height of the rendered SVG. See width.
loadExternalStyleSheets boolean <optional> Whether external style sheets referenced by SVG link elements or xml-stylesheets shall be loaded using HTTP requests. Note, that all style sheets that cannot be accessed because of CORS policies are ignored. The default is false.

Screenshots
N/A

Desktop (please complete the following information):

  • OS: Linux (Pop OS — Ubuntu derivative)
  • Browser: Firefox
  • Version: 103.0

Smartphone (please complete the following information):
N/A

Additional context
Some react examples for your code would be really useful. All the examples I found rely on document.getElementById or some combination of parsing SVG text and then picking sometimes the first child and sometimes not.

If it’s of any use I got my original jsPDF code from here: https://codesandbox.io/s/generate-pdf-using-jspdf-kom01x?file=/src/generatePdf/GeneratePdf.tsx

I then wanted to add a SVG to it.

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

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

Понравилась статья? Поделить с друзьями:
  • To be going to найти ошибки
  • Tmodloader что делать если выдает ошибку
  • Tmodloader ошибка при запуске мира
  • Tmodloader ошибка microsoft xna framework
  • Tmodloader game ran out of memory ошибка