You might have come across a use case where you need to format a number to fixed decimal places.
For example, you might want to format a number to 2 decimal places. You can use the toFixed()
method to do this.
1const num = 123.4562const formattedNum = num.toFixed(2)3console.log(formattedNum) // 123.46
However, sometimes you might get the following error while using the toFixed()
method.
1Uncaught TypeError: "num".toFixed is not a function
You will get this error because the toFixed()
method is only available for numbers. If you try to use it on a string, you will get the above error.
1const num = "123.456"2const formattedNum = num.toFixed(2)3console.log(formattedNum) // Uncaught TypeError: "num".toFixed is not a function
To fix this error, you have to convert the string to a number. You can use the Number()
method to convert a string to a number.
1const num = "123.456"2const formattedNum = Number(num).toFixed(2)3console.log(formattedNum) // 123.46
If you are still getting the error, then you have to check if the variable is a number or not. You can use the isNaN
function to check if the variable is a number or not.
1const numStr = "123.456"2const num = Number(numStr)3if (!isNaN(num)) {4 const formattedNum = num.toFixed(2)5 console.log(formattedNum)6} else {7 console.log("The variable is not a number")8}
Do follow me on twitter where I post developer insights more often!