1

I'm trying to sum two variables like this:

xValue is 2.00000000 (positive)

yValue is -0.00001250 (negative)

<%= xValue.toFixed(8) + yValue.toFixed(8) %>

The output is becoming: 2.00000000-0.00001250

But I need to see this : = 1.9999875

If I extract variables :

<%= xValue.toFixed(8) - yValue.toFixed(8) %>

There is no problem : = 2.0000125

What I'm doing wrong?

Lazy
  • 1,807
  • 4
  • 29
  • 49

1 Answers1

5

First of all, Number.toFixed(n) returns a string (with n digits after a decimal point), not a number. If you want to do math with numbers, pushing them through toFixed is usually not a good idea (as for any math they should be converted back to Number type).

Second, + operation is overloaded in JS: for numbers, it's addition, but for strings (even if just one operand is a string), it's concatenation of operands. That's exactly what happened in your case: two strings - representing positive and negative numbers - were just glued together.

(it's not the same, btw, for the rest of arithmetic operations; hence the correct result of -).

Overall, here's one possible approach to express what you want:

<%= (xValue + yValue).toFixed(8) %>

... but here's a caveat: float math in JS is flawed by design. You only deal with approximations of float values that can be stored in memory. Most of the time, these approximations will be correctly rounded by toFixed(), but sometimes, they won't.

Community
  • 1
  • 1
raina77ow
  • 103,633
  • 15
  • 192
  • 229