Possible Duplicate:
Is JavaScript's Math broken?
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...)
Approach 1: Given two or more numbers to sum up the float numbers. Use parseFloat() and toFixed() method to format the output accordingly.
Split both the given floating-point number in form of a string with respect to the decimal point to separate the fractional and integer part of the numbers. Add the fractional and integer part of the two numbers separately and forward the final carry part of fractional addition to integers part.
Unlike many other programming languages, JavaScript does not define different types of numbers, like integers, short, long, floating-point etc. JavaScript numbers are always stored as double precision floating point numbers, following the international IEEE 754 standard.
The float() method converts the string value returned by input() into a floating-point number. This allows us to multiply “value” and “discount” because they are both numbers.
Once you read what What Every Computer Scientist Should Know About Floating-Point Arithmetic you could use the .toFixed()
function:
var result = parseFloat('2.3') + parseFloat('2.4'); alert(result.toFixed(2));
(parseFloat('2.3') + parseFloat('2.4')).toFixed(1);
its going to give you solution i suppose
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With