adamwdraper / Numeral-js

A javascript library for formatting and manipulating numbers.
http://numeraljs.com
MIT License
9.66k stars 925 forks source link

numeral.format giving error for 9999999999999999999999999999 #545

Open harishcheruku opened 7 years ago

harishcheruku commented 7 years ago

Hi,

numeral(9999999999999999999999999999).format("0,00.00") this is giving error, funny part is,if you take a bigger number with 8's or 7's its working fine like: numeral(8888888888888888888888888888888).format("0,00.00") issue is only with 9's.

ERROR TEXT:

numeral.min.js:8 Uncaught TypeError: Cannot read property 'length' of undefined at i (numeral.min.js:8) at c (numeral.min.js:8) at a.format (numeral.min.js:8) at eval (eval at getFormattedVal (number.ts:114), :1:53) at NumberField.getFormattedVal (number.ts:94) at NumberField.displayChanged (number.ts:101) at View_NumberField1.handleEvent0 (/NumberModule/NumberField/component.ngfactory.js:74) at HTMLInputElement.eval (platform-browser.umd.min.js:14) at e.invokeTask (zone.min.js:1) at Object.onInvokeTask (core.umd.min.js:14) at e.invokeTask (zone.min.js:1) at t.runTask (zone.min.js:1) at HTMLInputElement.invoke (zone.min.js:1)

jpmunz commented 7 years ago

Was hitting a similar error with: numeral(1e+33).format('0.[0]a')

However doing: numeral(1e+32).format('0.[0]a')

"100000000000000000000t"

Works fine. Looks like this is due to passing a large number to the native toFixed function and getting different behavior, from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed:

"If numObj is greater than 1e+21, this method simply calls Number.prototype.toString() and returns a string in exponential notation"

With the format I'm using the value is reduced by a power a of 12 and suffixed with the trillion abbreviation so everything smaller than 1+e33 works. Looks like the code was changed in the newest version so instead of erroring with 'length of undefined' it will now return NaN: https://github.com/adamwdraper/Numeral-js/blob/master/src/numeral.js#L197