0

I am using node-mysql and have 2 rows. I am adding together the 'total' column which values are 1.10 and 1.16 obviously expecting total to be 2.26

I am querying the table, and the adding them as follows:

connection.query(q3, function (err, results) {
    if (err) throw err;
    var totalSum=0;
    for(i=0; i<results.length;i++) {
        totalSum = totalSum + parseFloat(results[i].total).toFixed(2);
    }

However my totalSum returns as 01.101.16 which shows as a concatenation of strings. Why is my parseFloat not changing the string obtained from sql?

Thanks

5
  • .toFixed() returns a string, not a number. Commented Apr 12, 2016 at 14:58
  • try Number(results[i]) Commented Apr 12, 2016 at 14:59
  • @maioman if the .toFixed() is still there that will make absolutely no difference. Commented Apr 12, 2016 at 15:00
  • Ha.. so simple. thanks will accept when it lets me Commented Apr 12, 2016 at 15:00
  • @Pointy I meant Number( (results[i].total).toFixed(2) ) for converting it back to number but OP shouldn't use toFixed(2) to begin with Commented Apr 12, 2016 at 15:13

3 Answers 3

3

If you want to format the sum as a number with two places past the decimal point, do so after the total has been calculated. The .toFixed() function returns a string, not a number.

Sign up to request clarification or add additional context in comments.

Comments

0

Try this:

totalSum = (totalSum + parseFloat(results[i].total)).toFixed(2);

1 Comment

Because .toFixed(2) will return a string, this will have exactly the same problem as the original.
0

There is no point to use toFixed within the loop. It should be called on the sum.

let totalSum = results.reduce((prev,curr) => prev.total + curr.total).toFixed(2);

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.