2

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.

User
  • 45
  • 1
  • 10
  • How can I achieve without using minimumFractionDigits? maximumFractionDigits? – User Sep 25 '17 at 10:52
  • Check updated answer – Brahma Dev Sep 25 '17 at 11:02
  • Possible duplicate of [Formatting Number in javascript without using minimumFractionDigits, maximumFractionDigits](https://stackoverflow.com/questions/46403486/formatting-number-in-javascript-without-using-minimumfractiondigits-maximumfrac) – Brahma Dev Sep 26 '17 at 15:22

2 Answers2

2

var num = 123456789;
console.log(num.toLocaleString(undefined, {minimumFractionDigits: 3, maximumFractionDigits: 3}));

Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString

undefined will use user's locale, you might want to specify a custom one.


Updated answer

var number = 12345678;
console.log(parseInt(number*1000).toLocaleString("en-US").replace(/\,([^\,]*)$/,"."+'$1'));
Brahma Dev
  • 1,955
  • 1
  • 12
  • 18
0

Use Intl.NumberFormat,

var number = 12345678.098;
alert(new Intl.NumberFormat().format(number));

Here's a FIDDLE

Parag Jadhav
  • 1,853
  • 2
  • 24
  • 41
  • You can add the `options` parameter to get the decimal behaviour (e.g. `12345678` -> `'12345678.00'`): `new Intl.NumberFormat(undefined, { minimumFractionDigits: 3, maximumFractionDigits: 3 }).format(number)`, or provide this to `Number.prototype.toLocaleString()` as @BrahmaDev has in his answer – Craig Ayre Sep 25 '17 at 09:40
  • What is your browser name & version? – Parag Jadhav Sep 25 '17 at 09:41
  • @BrahmaDev Check your [`Browser Compatibility`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat) – Parag Jadhav Sep 25 '17 at 09:44
  • @CraigAyre the output is dependent on browser version – Parag Jadhav Sep 25 '17 at 09:47
  • I'm getting Intl undefined error while running in IE – User Sep 25 '17 at 10:38