javascript - Why are some scientific numbers automatically rounded and others aren't? -
why numbers in scientific notation starting 9.999999999999999 rounded 1 while others remain same?
for example, in google chrome 20 following happens.
(9.999999999999999e+306).tostring() === "9.999999999999999e+306" // true
but
(9.999999999999999e+303).tostring() === "1e+304" // true
why that? floating point issue?
however strangest thing in opera 11.64 (1e23).tostring() === "9.999999999999999e+22"
. tried report 1e23 bug opera no 1 replied.
live demo here: http://jsfiddle.net/3ekdk/3/
source code of demo
var console = console || {}; console.logtobody = function( str ){ document.body.innerhtml += "" + str + "<br/>"; }; var parts = ["9.999999999999999e", 310 ], tmp, tmp2; while( parts[1]-- ){ tmp = +(parts.join('')); if( /9.9{3,}e/.test( +tmp ) ){ console.logtobody( tmp + " doesn't convert " + (+tmp).toprecision(1) ); } tmp2 = "1e"+parts[1]; //carakan javascript engine math bug: if( !/^1e*/.test( +tmp2 ) ){ console.logtobody( tmp2 + " = " + (+tmp2) + " in runtime environment."); } }
it's because floating point numbers approximation. numbers can't represented floating point format, is, binary fraction, approximated http://en.wikipedia.org/wiki/ieee_754-2008
that why should never rely on floating point arithmetic without rounding it. simple example following:
> 20.61 - .1 20.509999999999998
here's great explanation of floating point format http://www.randelshofer.ch/fhw/gri/float.html#chapterfloatingpointformat
ordinary decimal 178.125
scientific decimal 1.78125 e 102
scientific binary 1.0110010001 e 2111
Comments
Post a Comment