Skip to content

toFixed returns a string, not a number

Quick summary

You did price.toFixed(2) + shipping — toFixed returned a string, so + concatenated instead of adding.

Why this happens

  • Using the result of .toFixed in further arithmetic

  • Assigning toFixed output to a variable typed as number

  • Chaining .toFixed with number methods that do not exist on strings

Minimal example

✗ Broken code
const price = 9.99;
const shipping = 5;
const total = price.toFixed(2) + shipping; // '9.995' — concatenation!
console.log(total);
✓ Fixed code
const price = 9.99;
const shipping = 5;
const total = (price + shipping).toFixed(2); // '14.99'
console.log(total);

toFixed returns a string, so adding it to a number concatenates. Doing the arithmetic first and calling toFixed only at the end gives the correct numeric total formatted as a string.

How to diagnose

  • Check typeof of the value after .toFixed — it is 'string'

  • Print the expression result to spot concatenation like '9.995'

  • Look for .toFixed results flowing into numeric operations

How to fix

  • Convert back with Number(price.toFixed(2)) if a number is needed

  • Do all arithmetic before calling .toFixed, only at display time

  • Use a decimal library that returns numbers for money math

How to prevent

  • Call .toFixed only at the final display step, never mid-calculation

  • Use TypeScript to flag string results used as numbers

Related Resources

Related Glossary

Related Lessons

← Back to language