Float sum with javascript

129,975

Solution 1

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));​

Solution 2

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

its going to give you solution i suppose

Share:
129,975
davioooh
Author by

davioooh

Hi, I'm David Castelletti. I like to create things with Java & Kotlin (❤). LinkedIn profile Personal Page + Blog (italian)

Updated on September 21, 2020

Comments

  • davioooh
    davioooh over 3 years

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

  • Muhammad Musavi
    Muhammad Musavi almost 6 years
    Simply use parseFloat((2.3 + 2.4).toFixed(10)) Here is the explanation
  • Artem Fedotov
    Artem Fedotov over 3 years
    Pay attention that toFixed(fractionDigits) returns a string
  • Monzur
    Monzur over 2 years
    this is not a real solutions whereas my numbers are different 1+1.2+1.25+4.5=???
  • RobG
    RobG over 2 years
    @Monzur—you can do toFixed on the result: Number((1+1.2+1.25+4.5).toFixed(10)) will return a number. If you need more than 10 decimal places you might need to use BigInt instead.