. Advertisement .
. Advertisement .
Why Does This Error Occur?
Before we dive into the solution, it helps to analyze why the error occurred in the first place.
Overall, this error takes place whenever you call the method toFixed() on one value that isn’t a number. Hence, whichever solution you choose, you must make sure the numbers are involved: either convert that value to numbers or only use the method toFixed() on numbers in the first place.
Keep these three methods in mind:
- Method 1. Convert strings to numbers
- Method 2. Parse a value to numbers
- Method 3. Assess the variable category
The next section will delve further into specific examples for each approach.
Method 1. Convert Strings to Numbers
The method toFixed() formats number. However, your faulty code currently entails type strings, which is why string concatenation happens instead of an arithmetic addition. Hence, the solution is to convert them into numbers first.
- The original code:
var totalSum = (grandTotal + getDeliveryCost).toFixed(3);
- The new code after conversion:
var totalSum = (Number(grandTotal) + Number(getDeliveryCost)).toFixed(3);
- The error:
const num = '234'; // Uncaught TypeError: num.toFixed is not a function const result = num.toFixed(2);
- The solution:
const num = '234.567'; const result = Number(num).toFixed(2); console.log(result);
Method 2. Parse A Value to Numbers
The method ToFixed is unavailable for non-number values, which is why you should parse a value to a Number first. Only then can you pick up the method ToFixed.
In this example, we picked up a ternary operator, quite similar to the statement if/else. Next, we checked whether that num variable contains numbers. If the answer is a yes, the system will return the outcome of calling Tofixed.
const num = null; const result = typeof num === 'number' ? num.toFixed(2) : 1; console.log(result);
let str = `234.234567` console.log(Number(str).toFixed(3)) console.error(str.toFixed(3))
Method 3. Assess the Variable Category
The last solution can be of help should the previous two fail. While we cannot guarantee 100% success, they sometimes work, so try it out!
All in all, only int and float values have a toFixed method. Hence, you can console the variable to identify its type.
The wrong code (resulting in error):
console.log(("5" + 6).toFixed(3));
The right code (which means it’s working):
console.log((6 + 6).toFixed(3));
Leave a comment