diff --git a/accounting.js b/accounting.js index fd181fd..791069b 100644 --- a/accounting.js +++ b/accounting.js @@ -216,9 +216,11 @@ var toFixed = lib.toFixed = function(value, precision) { precision = checkPrecision(precision, lib.settings.number.precision); - var exponentialForm = Number(lib.unformat(value) + 'e' + precision); - var rounded = Math.round(exponentialForm); - var finalResult = Number(rounded + 'e-' + precision).toFixed(precision); + var shiftedExponentials = String(lib.unformat(value)).split('e'); + var shiftedNumber = Number(shiftedExponentials[0] + 'e' + ((shiftedExponentials[1] ? Number(shiftedExponentials[1]) : 0) + precision)); + var rounded = Math.round(shiftedNumber); + var roundedExponentials = String(rounded).split('e'); + var finalResult = Number(roundedExponentials[0] + 'e' + ((roundedExponentials[1] ? Number(roundedExponentials[1]) : 0) - precision)).toFixed(precision); return finalResult; }; diff --git a/tests/jasmine/core/formatNumberSpec.js b/tests/jasmine/core/formatNumberSpec.js index 46df133..34f5990 100644 --- a/tests/jasmine/core/formatNumberSpec.js +++ b/tests/jasmine/core/formatNumberSpec.js @@ -21,6 +21,14 @@ describe('formatNumber', function(){ }); + it('should format tiny numbers without returning NaN', function(){ + + expect( accounting.formatNumber(1e-7) ).toBe( '0' ); + expect( accounting.formatNumber(0.0000001) ).toBe( '0' ); + expect( accounting.formatNumber(1e-7, 8) ).toBe( '0.00000010' ); + + }); + it('should work for large numbers', function(){ expect( accounting.formatNumber(123456.54321, 0) ).toBe( '123,457' );