Tuesday, 12 December 2017

math - Float sum with javascript













I'm
calculating the sum of several float values using javascript and... I've noticed a
strange thing never seen before. Executing this
code:



parseFloat('2.3') +
parseFloat('2.4')


I
obtain
4.699999999999999




So...
what sould I do to obtain a correct value? (supposed that this is
incorrect...)


itemprop="text">
class="normal">Answer



Once you
read what href="http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html">What
Every Computer Scientist Should Know About Floating-Point
Arithmetic
you could use the href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Number/toFixed">.toFixed()
function:



var result =
parseFloat('2.3') +
parseFloat('2.4');
alert(result.toFixed(2));​


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...