What is the toFixed() method in TypeScript?
Overview
The toFixed() method rounds the given number to a specified number of decimals. It will add zeroes if the given number of decimals is higher than the number.
We will use the following syntax to call this method.
Syntax
number.toFixed(x)
Parameters
It will take the number of decimals as a parameter, which is optional. The default is 0.
Return value
It returns a string with or without decimals according to the given parameter. Let's take a look at an example of this.
Code
//given numberlet num = 5.56789;//use of toFixed method without parameterlet n = num.toFixed();console.log(n)//use of toFixed method with parametern = num.toFixed(10);console.log(n)
Explanation
- Line 2: We declare and initialize the number
num. - Line 5: We round the number with
0decimals using thetoFixed()method without passing any parameter. - Line 7: We print the result returned in line 5.
- Line 10: We round the number with
10decimals using thetoFixed()method by passing10as a parameter. It will add zeroes since we pass the decimals higher than the number. - Line 12: We print the result returned in line 10.