TypeError: toFixed is not a function in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

TypeError: toFixed is not a function in JavaScript #

The "toFixed is not a function" error occurs when the toFixed() method is called on a value that is not a number. To solve the error, either convert the value to a number before calling the toFixed method or only call the method on numbers.

typeerror tofixed is not a function

Here is an example of how the error occurs.

index.js
const num = '123'; // ⛔️ Uncaught TypeError: num.toFixed is not a function const result = num.toFixed(2);

We called the Number.toFixed method on a value that has a type of string, which caused the error.

To solve the error, convert the value to a number before calling the toFixed() method.

index.js
const num = '123.456'; const result = Number(num).toFixed(2); console.log(result); // 👉️ 123.46

If you know that the value is a valid number that is wrapped in a string, pass it to the Number object before calling the toFixed() method.

Alternatively, you can check if the value has a type of number before calling the toFixed method.
index.js
const num = null; const result = typeof num === 'number' ? num.toFixed(2) : 0; console.log(result); // 👉️ 0

We used the ternary operator, which is very similar to an if/else statement.

If the expression to the left of the question mark evaluates to a truthy value, we return the value to the left of the colon, otherwise the value to the right is returned.

We check if the num variable stores a number, and if it does, we return the result of calling the toFixed method, otherwise we return 0.

If the error persists, console.log the value you're calling the toFixed method on and log its type using the typeof operator.

If the value is an object or array, you should probably be accessing a specific property on the object or a specific index in the array before calling the toFixed() method.

Conclusion #

The "toFixed is not a function" error occurs when the toFixed() method is called on a value that is not a number. To solve the error, either convert the value to a number before calling the toFixed method or only call the method on numbers.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.