Last updated: Mar 2, 2024
Reading timeยท2 min

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.

Here is an example of how the error occurs.
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 the error occurred.
number before calling the toFixed() methodTo solve the error, convert the value to a number before calling the toFixed()
method.
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() constructor before calling the toFixed() method.
You can also use the parseFloat function to convert a value to a number.
const num = '123.456ABC'; const result = parseFloat(num).toFixed(2); console.log(result); // ๐๏ธ 123.46
The parseFloat() function returns a floating-point number parsed from the
given string or NaN if the first non-whitespace character cannot be converted
to a number.
The Number.toFixed() method formats a number using fixed-point notation and
can only be called on numbers.
number before calling toFixed()Alternatively, you can
check if the value has a type of number
before calling the toFixed method.
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.
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.
You can also use a simple if/else statement to check if the value is a number
before calling the toFixed() method.
const num = null; let result = 0; if (typeof num === 'number') { result = num.toFixed(2); } console.log(result); // ๐๏ธ 0

If the value is a number, we call the toFixed() method on it, otherwise, the
result variable remains set to 0.
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.