Number Formatter

Formats numbers with proper thousand separators and decimal places. Handles currencies, percentages, and large numbers.

JavaScript7/16/2025
#utilities#formatting#numbers
JavaScript
function formatNumber(num, options = {}) {
  const {
    decimals = 2,
    separator = ',',
    decimal = '.',
    prefix = '',
    suffix = ''
  } = options;

  const numStr = Math.abs(num).toFixed(decimals);
  const [integer, fraction] = numStr.split('.');
  
  const formattedInteger = integer.replace(/\B(?=(\d{3})+(?!\d))/g, separator);
  const formattedNumber = fraction ? `${formattedInteger}${decimal}${fraction}` : formattedInteger;
  
  return `${prefix}${num < 0 ? '-' : ''}${formattedNumber}${suffix}`;
}
...
Loading comments...