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 being: 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?
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 being: 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?
Share asked Sep 9, 2014 at 20:43 LazyLazy 1,8374 gold badges29 silver badges52 bronze badges1 Answer
Reset to default 5First 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.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744911639a4600587.html
评论列表(0条)