-1

I am stuck at one point,like how can i put a comma separator to a decimal number which are fixed to two decimals

example: 50506.2569 to 50,506.25

what i am doing is

var variable = 32568.595;
var fix = variable.toFixed(2)
var seperator = fix.toLocaleString('en-in')
console.log(seperator);

this one is giving me 32568.60 but i am trying to get 32,568.60

vivek singh
  • 417
  • 2
  • 12
  • 36

3 Answers3

0

This will format your numbers the way you want

function formatNumber(amount) {
  const options = {
    style: 'decimal',
    maximumFractionDigits: 2
  }
  const formatter = new Intl.NumberFormat('en-US', options)
  return formatter.format(amount)
}

console.log(formatNumber(50506.2569))
Prithwee Das
  • 4,628
  • 2
  • 16
  • 28
0
var variable = 32568.595;
variable = +variable.toFixed(2); // Limit to 2 numbers after comma
variable = variable.toLocaleString(); // Make separator ','

This should work

0

console.log(format(32568.595));
console.log(format(32568));
console.log(format(32568.595, 0));


function format(number, decimals = 2, locale = 'en-in') {
 const fixed = number.toFixed(decimals);
 const [int, dec] = fixed.split('.')
 const intFormatted = (+int).toLocaleString(locale)

 return intFormatted + (dec ? '.' + dec : '');
}
AlexOwl
  • 869
  • 5
  • 11