0

I want to perform addition of floating point numbers. I will always have always have only 2 decimal places.

However if I do:

         var num = 0;
         num += parseFloat("2434545.64").toFixed(2);
         num += parseFloat("454560.91").toFixed(2);

I get the value as 02434545.64454560.91 It is appending instead of adding. Also will the addition be accurate always?

2 Answers 2

5

toFixed() return a String. So you concatenate two String.
You should use toFixed() only in the last statement and you should not mix this invocation with a += operator in a even statement because here :

num += parseFloat("2434545.64").toFixed(2);

parseFloat("2434545.64").toFixed(2) is evaluated first.
It produces a String.
Then its num += String result is evaluated.
So, it would concatenate a Float with a String. Which produces again a String concatenation and not an arithmetic operation.

Just invoke toFixed() in a distinct statement :

var num = 0;
num += parseFloat("2434545.64");
num += parseFloat("454560.91");
num = num.toFixed(2);
Sign up to request clarification or add additional context in comments.

Comments

0

Here you go with the solution

var num = 0;
     num += 2434545.64;
     num += 454560.91;
console.log(parseFloat(num).toFixed(2));

Here is the documentation for parseFloat https://www.w3schools.com/jsref/jsref_parsefloat.asp

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.