toFixed vs toPrecision in JavaScript
Intermediate · 3 min read
When you show a price on screen, you want 3.14, not 3.14159, and 5.00, not 5. JavaScript has two built-in methods for this: toFixed and toPrecision. They look alike, but they count different things, and both hand you back text rather than a number.
In this tutorial you will format 3.14159 to two decimal places, check what type comes back, find a number that toFixed seems to round the wrong way, and see what toPrecision counts instead. You need to know what typeof does.
Methods on a number
toFixed and toPrecision are methods: functions that belong to a value and are called with a dot. You call them on a number, like price.toFixed(2).
If you write the number directly, wrap it in brackets: (5).toFixed(2). Without the brackets, 5.toFixed(2) is a syntax error, because JavaScript reads 5. as the start of a decimal number.
Decimal places vs significant figures
These are two ways to say "how many digits":
- Decimal places count digits after the point. 1234.57 has two.
- Significant figures count digits from the first non-zero one. 1234.57 has six.
toFixed counts decimal places. toPrecision counts significant figures.
Here is the exercise. Try it first if you like, then read on and we will work through it together.
8 toFixed returns a string, and toPrecision counts differently
fairFormat 3.14159 to two decimal places and check the type of what comes back. Then show that (0.615).toFixed(2) is not '0.62', and say what toPrecision counts instead.
Stuck? Three hints, smallest first
- 1.
toFixedis a method on a number and it returns a string, padded with zeros. - 2.
toPrecisioncounts significant figures, and switches to exponential form when the number needs it. - 3. Adding two
toFixedresults concatenates them, which is the bug this always causes.
Step 1: two decimal places
const price = 3.14159;
console.log(price.toFixed(2)); // 3.14
console.log(typeof price.toFixed(2)); // string
The result looks like a number, but typeof says string. toFixed is made for showing values, and a string can hold things a number can't, like trailing zeros:
console.log((5).toFixed(2)); // 5.00
Step 2: the string trap
Because the result is text, + joins two of them instead of adding:
console.log((1.5).toFixed(1) + (2.5).toFixed(1)); // 1.52.5
You wanted 4. You got '1.5' glued to '2.5'. This is a real bug on receipts and invoices: someone formats each line, then adds the formatted values.
If you need a number back, convert with Number:
const price = 3.14159;
console.log(Number(price.toFixed(2))); // 3.14
The safer habit is to do all your math on numbers, and call toFixed only at the very end, when the value goes on screen.
Step 3: 0.615 rounds down
Two decimal places of 0.615 should be 0.62, right? Run it:
console.log((0.615).toFixed(2)); // 0.61
console.log((0.615).toFixed(20)); // 0.61499999999999999112
console.log((1.005).toFixed(2)); // 1.00
The second line explains the first. Computers store decimals in binary, and 0.615 can't be stored exactly. The closest stored value is a tiny bit under 0.615, and toFixed(20) shows those hidden digits. toFixed rounds the value that is really stored, which is below the halfway point, so rounding down is correct. 1.005 has the same problem.
toFixed isn't sloppy here. The number you typed and the number in memory are just slightly different.
Step 4: significant figures with toPrecision
console.log((1234.5678).toPrecision(6)); // 1234.57
console.log((123456).toPrecision(2)); // 1.2e+5
console.log((0.000123).toPrecision(3)); // 0.000123
The first line keeps six significant figures: four before the point and two after. The second asks for only two figures of 123456. There is no way to write that as an ordinary number without extra zeros, so JavaScript switches to exponential notation: 1.2e+5 means 1.2 times 10 to the 5th, or 120,000. The third keeps three figures, and the leading zeros don't count.
toPrecision also returns a string. It suits scientific values, where size varies a lot. For money, use toFixed, so every price has exactly two decimal places.
The full solution
The answer panel formats 3.14159, pads 5 to 5.00, shows 0.615 rounding to 0.61 along with its stored digits, compares toPrecision, and repeats the string-joining bug. The checks underneath confirm every result. Press Run to see the output.
const price = 3.14159;
console.log('toFixed(2) :', price.toFixed(2), 'typeof', typeof price.toFixed(2));
console.log('back to a number :', Number(price.toFixed(2)));
console.log('(5).toFixed(2) :', (5).toFixed(2), '<- padded');
console.log('(0.615).toFixed(2):', (0.615).toFixed(2), '<- not 0.62');
console.log('the stored value :', (0.615).toFixed(20));
console.log('toPrecision(6) :', (1234.5678).toPrecision(6));
console.log('toPrecision(2) :', (123456).toPrecision(2), '<- exponential');
console.log('adding two strings:', (1.5).toFixed(1) + (2.5).toFixed(1));
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('toFixed returns a string', typeof price.toFixed(2), 'string');
test('so it needs converting before arithmetic', Number(price.toFixed(2)), 3.14);
test('it pads with zeros rather than dropping them', (5).toFixed(2), '5.00');
test('0.615 to two places is 0.61, not 0.62', (0.615).toFixed(2), '0.61');
test('because what is stored is a hair under 0.615', (0.615).toFixed(20), '0.61499999999999999112');
test('1.005 fails the same way', (1.005).toFixed(2), '1.00');
test('toPrecision counts significant figures, not decimals', (1234.5678).toPrecision(6), '1234.57');
test('and switches to exponential when the figures run out', (123456).toPrecision(2), '1.2e+5');
test('adding two toFixed results concatenates them', (1.5).toFixed(1) + (2.5).toFixed(1), '1.52.5');
toFixed is for display and nothing else. The last assertion is the bug it causes in production: two subtotals formatted for a receipt, added with +, and the total is "1.52.5". Format at the very last step, never before arithmetic.
0.615 is the honest example to keep. toFixed is not sloppy — it rounds the value that is actually stored, and that value is below the halfway point, so rounding down is correct. The digits after position 17 in the toFixed(20) assertion are what the reader is usually never shown.
toPrecision answers a different question: three significant figures of 0.000123 is 0.000123, three of 123456 is 1.23e+5. Use it for scientific output, and never for money.
Common mistakes
- Adding
toFixedresults. They are strings, so+joins them. Add the numbers first, format once at the end. - Writing
5.toFixed(2). That is a syntax error. Write(5).toFixed(2). - Using
toPrecisionfor prices. It counts significant figures, so(1234.5).toPrecision(3)gives1.23e+3, not a price.
Try it yourself
- Format 7 to three decimal places. What does the string look like?
- Use
toFixed(20)to look at what 0.1 and 0.5 are really stored as. Which one is exact? - Write
formatNaira(n)that returns a string like'₦1250.00'for 1250.