[TIL] a little number formatter in Javascript

Mykolas Mankevicius - Nov 22 '21 - - Dev Community

For those who want to transform numbers into to nicer strings, here's a little snippet of code that can help you out:

const isItANumber = (str) => {
  return /^-?[0-9]+(e[0-9]+)?(\.[0-9]+)?$/.test(str);
};

const formatNumber = (value, format = true) => {
  if (!format) {
    return value;
  }

  // This use case is specific to my project, you can delete it
  if (!isItANumber(value)) {
    return value;
  }
  const number = Number.parseFloat(value);
  if (typeof number !== 'number' || Number.isNaN(number)) {
    return value;
  }

  // 'en-US' is my specific use case, you can choose whatever you want, or leave it empty for client specific locale
  return number.toLocaleString('en-US');
};

console.log(formatNumber(717140.87)); // '717,140.87'
console.log(formatNumber(-717140.87)); // '-717,140.87'
// This use case is specific to my project, you can delete it
console.log(formatNumber('-71,714,087 units')); // '-71,714,087 units'
Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player