Solve - toFixed is not a function Error in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 19 20212 min read

Solve - toFixed is not a function Error #

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, so we got the error back.

To solve this, we can 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 you can safely 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 a 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, if it does, we return the result of calling the toFixed method on it, otherwise return 0.

If the error still persists, console.log the value you're calling thetoFixed method on and also 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, which stores a number, before calling the toFixed() method.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee