1

How can I convert the comma separated value with some decimal value round off to two places.

Example:
var number = '4,500.02734'
output: 4, 500.03
sanin
  • 264
  • 1
  • 5
  • 18

3 Answers3

4

This requires two operations...

  1. Parse the number string into a Number instance

    const actualNumber = +number.replace(/,/g, '') // produces 4500.02734
    
  2. Format the string to a given locale with a maximum of 2 decimal places

    const formatted = actualNumber.toLocaleString('en-US', {maximumFractionDigits: 2})
    

var number = '4,500.02734'

const actualNumber = +number.replace(/,/g, '')
const formatted = actualNumber.toLocaleString('en-US', {maximumFractionDigits: 2})

document.write(formatted)
Phil
  • 157,677
  • 23
  • 242
  • 245
3

You can use this simple function that will convert your number to comma separated value and decimal number round off as well.

var number = 5000000.245;
document.write(format_number(number));

function format_number(n) {
  return n.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,");
}
nas
  • 2,289
  • 5
  • 32
  • 67
1
function format(a) {
    var i=a.indexOf(".");
    var f=(parseFloat("0"+a.substring(i)).toFixed(2)).toString();
    return a.substring(0,i)+"."+f.substring(2,f.length);
}

format("4,500.02734") outputs 4,500.03.

Richard Yan
  • 1,276
  • 10
  • 21