format numbers in javascript code example

Example 1: format amount in javascript

const formatToCurrency = amount => {
  return "$" + amount.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, "$&,");
};
formatToCurrency(12.34546); //"$12.35"
formatToCurrency(42345255.356); //"$42,345,255.36

Example 2: how to number format in javascript

function formatNumber(num) {
  return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,')
}

console.info(formatNumber(2665)) // 2,665
console.info(formatNumber(102665)) // 102,665
console.info(formatNumber(111102665)) // 111,102,665
console.info(formatNumber(1240.5)) // 1,240.5
console.info(formatNumber(1000240.5)) // 1,000,240.5