How do you format and parse numbers in JavaScript?
Numbers are formatted with methods that belong to the number itself, and they are read back with the Number function or with the parseInt() and parseFloat() functions. The first thing to know is that the formatting methods give you a string and not a number, because a fixed number of decimal places is not something that the number type is able to hold.
const price = 19.5;
console.log(price.toFixed(2)); // '19.50', and it is a string
console.log(price.toFixed(0)); // '20'
console.log((0.1 + 0.2).toFixed(2)); // '0.30'
console.log((1234.5678).toPrecision(6)); // '1234.57'
console.log((0.000123).toPrecision(2)); // '0.00012'
console.log((255).toString(16)); // 'ff'
console.log((5).toString(2)); // '101'
console.log(Number('42')); // 42
console.log(parseFloat('3.5rem')); // 3.5
console.log(parseInt('42px', 10)); // 42
The toFixed() method takes the number of digits after the decimal point, and it pads or rounds the value to that width. The toPrecision() method takes the total number of important digits, and that is a different thing, which matters for very small and very large numbers. A very small number printed with toFixed() can give you a long string of zeros, while toPrecision() gives you the important digits.
The toString() method takes a base, so you can convert a number to hexadecimal, binary, or octal. It also accepts any base between 2 and 36.
For reading numbers back out of text, the Number function is strict. It converts the whole string, it ignores whitespace around the edges, and it gives you a value that is not a number if any part of the string is not numeric. The parseInt() and parseFloat() functions are lenient. They read the leading number and then stop at the first character that they cannot use. That is the right behaviour for a value like '42px', and it is the wrong behaviour when you are validating input, which is why you should reach for Number() when you want to reject bad text.