Math.round() doesn't follow specification for exact 0.5 #1621
Replies: 8 comments
-
Posted at 2019-08-11 by @MaBecker If you like take a look at the source code to find and fix the error ;-) |
Beta Was this translation helpful? Give feedback.
-
Posted at 2019-08-12 by @MaBecker Or it it might be related to this issue |
Beta Was this translation helpful? Give feedback.
-
Posted at 2019-08-27 by @gfwilliams Just to add:
So this would appear not to be a parsing issue (like 1573) but is to do with the rounding code itself |
Beta Was this translation helpful? Give feedback.
-
Posted at 2022-08-12 by user147930 It seems like Math.round() is a better solution, but it is not! In some cases it will NOT round correctly. Also, toFixed() will NOT round correctly in some cases. To correct the rounding problem with the previous Math.round() and toFixed(), you can define a custom JavaScript round function that performs a "nearly equal" test to determine whether a fractional value is sufficiently close to a midpoint value to be subject to midpoint rounding. The following function return the value of the given number rounded to the nearest integer accurately. Number.prototype.roundTo = function(decimal) { var num = 9.7654; |
Beta Was this translation helpful? Give feedback.
-
Posted at 2022-08-12 by @gfwilliams Do you think this is an issue specific to Espruino? If so, maybe you could look at helping to contribute a fix for it? |
Beta Was this translation helpful? Give feedback.
-
Posted at 2022-08-24 by @yerpj I also think Math.round() does not behave as expected
|
Beta Was this translation helpful? Give feedback.
-
Posted at 2022-08-24 by @gfwilliams Thanks - just created a new issue for this: espruino/Espruino#2258 Not sure how that happened as that's pretty much the first thing you'd test when implementing Math.round! |
Beta Was this translation helpful? Give feedback.
-
Posted at 2022-08-29 by rigrig That reminds me: I was planning to report
but totally forgot about it (whoops). Edit: reported now |
Beta Was this translation helpful? Give feedback.
-
Posted at 2019-08-11 by Robin
Sun 2019.08.11
While rounding towards positive infinity does work for negative numbers, it is not rounding
correctly for exact 0.5 values.
EDIT:
Had a thought, could this anomaly be related to the floating point number of digits to right of zero not matching different browsers and node.js output? hmmmm. . . .
EDIT: Tue 2019.08.20 > see snippet that may be helpful in resolving this > http://forum.espruino.com/comments/14867790/
Beta Was this translation helpful? Give feedback.
All reactions