2

I have the following big number: 2.9364136545300044e+24 I heed to format this value to 2,936,413.65 value

How could I do it of are there any libraries to make it?

Erik
  • 14,060
  • 49
  • 132
  • 218

2 Answers2

2

You can use Intl.NumberFormat.prototype.format, String.prototype.slice(), String.prototype.concat()

var number = 2.9364136545300044e+24;
var n = new Intl.NumberFormat().format(number);
var res = n.slice(0, 9).concat(".").concat(n.slice(10, 12));
console.log(res);
guest271314
  • 1
  • 15
  • 104
  • 177
  • Thanks for the answer. Is there polyfill for this API ? – Erik Oct 30 '16 at 17:13
  • @Erik What do you mean by "polyfill"? Which browser are you trying at? – guest271314 Oct 30 '16 at 17:14
  • I need to support IE9+ :( – Erik Oct 30 '16 at 17:15
  • The browser compatibility chart lists ie11+ as being supported. Have not checked for polyfills. You should be able to return same result using `.slice()`, `.concat()` alone; or alternatively including use of `.replace()` where the object and method are not supported at the browser. – guest271314 Oct 30 '16 at 17:17
  • 3
    I've found that `number.toLocaleString()` returns same result as yours `new Intl.NumberFormat().format` ) – Erik Oct 30 '16 at 17:39
  • 1
    @Erik If that's a locale specific format though, I wouldn't rely on that. Different users may get different results. – Carcigenicate Oct 30 '16 at 18:32
  • I think @Erik is correct, as different countries expect different formats in a front end scenario. Some countries separate thousands with . and others with , – htafoya Apr 04 '19 at 22:00
0

As a quick and easy solution you can use number.toLocaleString().

Since, the localString is based on Browser definition different users may get a different results. However, you can force a specific location to always get the same format. Ex: toLocaleString('en-GB', { timeZone: 'UTC' })

XAronX
  • 54
  • 1
  • 10