Per the always useful MDN, here’s the syntax:
There’s only one (optional) parameter for this method:
digits: This is the number of digits you want after the decimal point and can normally go up to 20. If you don’t specify anything, you get no numbers after the decimal point.
The toFixed() method returns a string, NOT a number, that has the exact number of digits that you specified with the digits parameter. MDN notes that it does not use scientific notation (e.g., 3E-4). It will round the number if the number is too long for the amount of digits, and if the number is too short it will add zeros on until it gets to the specified number of digits. Now, if numObj – that’s the number you’re giving it to modify; see the syntax above – is greater than 1e+21, first, wow, what are YOU working on? and second, it will call the toString() method and give you back a string in exponential notation.
There are two errors associated with the toFixed() method; in other words, that it “throws”. The first is RangeError and occurs if you send a value for digits that is not between 0 and 20 – although there are apparently ways to circumvent the 20. Giving a negative value would be absurd anyway – how do you get negative amounts of numbers after a decimal point? And no, that doesn’t tell it how many values to put in front of the decimal point!
The second error thrown by the toFixed() method is TypeError, and you get this if you try to send a letter or string, or NaN or null. It has to be a number.
So, let’s look at MDN’s examples:
var numObj = 12345.6789;
This is the number we are going to start with.
We didn’t specify a value for digit. toFixed() takes the number and looks at the decimal part – greater than 5, just like we all learned in math class, means you round up – and gives you back the rounded number with no decimal places.
We’ve specified 1 decimal place, and it has been rounded from .6789 to .7.
As MDN noted, we asked for 6 decimal places and the number only has 4, so the method added 2 zeros to get us to 6.
This gives you the original number, in decimal format rather than scientific notation, and since we gave it a 2 for the digits parameter, it adds the two decimal places on the end.