Format Numbers with Thousands Separators
Write the code, see it run, pass the checks.
The problem
- medium
- Code
Write formatNumber(value, options), where options is optional and may set decimals (default 0), thousands (the separator between groups of three digits, default ",") and point (the decimal point, default "."). Round the value to that many decimal places as toFixed does and always show exactly that many, then group the whole part in threes from the right. Negative numbers start with "-", except that a value which rounds to zero (such as -0.04 with 1 decimal) has no minus sign. So formatNumber(1234567.891, { decimals: 2 }) is "1,234,567.89", and with thousands "." and point "," it's "1.234.567,89". Don't use toLocaleString or Intl: a check switches them off. Halfway cases, such as rounding 2.5, aren't checked.
Your code must pass
- Groups whole numbers in threes
- Shows a fixed number of decimals
- Handles negative numbers
- Uses custom separators
- Doesn't use toLocaleString or Intl