Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Float sum with javascript [duplicate]

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...)

like image 311
davioooh Avatar asked Sep 20 '12 10:09

davioooh


People also ask

How do you sum a double value in JavaScript?

Approach 1: Given two or more numbers to sum up the float numbers. Use parseFloat() and toFixed() method to format the output accordingly.

How do you add two floats together?

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.

Does JavaScript have float and double?

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.

Can float multiply?

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.


2 Answers

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));​ 
like image 196
Darin Dimitrov Avatar answered Oct 19 '22 21:10

Darin Dimitrov


(parseFloat('2.3') + parseFloat('2.4')).toFixed(1); 

its going to give you solution i suppose

like image 24
Gyan Chandra Srivastava Avatar answered Oct 19 '22 20:10

Gyan Chandra Srivastava