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.