0

I have following types of values in a, b, c, d.

a= 12345678
b= 12345678.098
c=12345678.1
d=12345678.11

I need to format like,

a = 12,345,678.000
b=  12,345,678.098
c=12,345,678.100
d=12,345,678.110

I already tried tolocaleString() and toFixed(3) method. But I'm not able to works together of both method.

need your suggestion on this.

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
User
  • 45
  • 1
  • 10
  • You don't need any formatted numbers, numbers can't be formatted in JS. If you need "formatted numbers", the only chance is to convert the numbers to strings, and format those strings. – Teemu Sep 25 '17 at 10:56
  • https://stackoverflow.com/questions/46401854/formatting-number-in-javascript-using-decimal/46401920#46401920 – Parag Jadhav Sep 25 '17 at 10:57
  • 1
    This might help: https://stackoverflow.com/questions/149055/how-can-i-format-numbers-as-dollars-currency-string-in-javascript – Rajesh Sep 25 '17 at 10:57

1 Answers1

1

This might help you.

var a = 12345678;
var b = 12345678.098;
var c = 12345678.1;
var d = 12345678.11;

String.prototype.format = function() {
  return this.replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,");
};

function formatNumber(input) {
  return parseFloat(input).toFixed(3).toString().format();
}

console.log(formatNumber(a));
console.log(formatNumber(b));
console.log(formatNumber(c));
console.log(formatNumber(d));
Thusitha
  • 3,393
  • 3
  • 21
  • 33