Timeline for Solving round number in JS by using String
Current License: CC BY-SA 4.0
11 events
when toggle format | what | by | license | comment | |
---|---|---|---|---|---|
Nov 4, 2023 at 4:44 | answer | added | chux | timeline score: 1 | |
Sep 21, 2023 at 14:20 | comment | added | chux |
@Sébastien Josserand, The conversion of a number to a string can incur a roundings unless potentially hundreds of characters are used. Later attempting to round based on a >= '5' risks double rounding errors. This approach also has a problem with number = parseFloat(number.toFixed(4)); converting small values to zero. round() fails too many edge cases.
|
|
Aug 22, 2023 at 20:48 | vote | accept | Sébastien Josserand | ||
Aug 21, 2023 at 22:11 | comment | added | user555045 | My point was the value cannot be 1.04, it's impossible, there is no 64-bit float with that exact value. The best you can hope for is 1.04000000000000003552713678800500929355621337890625, which is the closest representable value to 1.04. However, printing that number gives 1.04, so it seems you get 1.04, but you don't. | |
Aug 21, 2023 at 22:03 | comment | added | Sébastien Josserand | If you call round(1.04000000000000003552713678800500929355621337890625, 2) you will get a type number which value 1.04. That's because by manipulating the char we get a string of "1.04" after truncating the right decimals. Then the parseFloat convert it to a number which is not only a printed value. I use this function after every sum or substract where decimals are implicated. I generated hundred of thousands accounting entries with this function, I had too much problems with the traditionnal methods. I generated a million of tests and compared with Math.round(number*100)/100 | |
Aug 21, 2023 at 21:09 | comment | added | user555045 | OK let me put that a bit differently: even if it is reliable (which I don't know for sure whether it is or isn't), I would not be able to reason about whether it is or isn't, so I cannot discover whether it is reliable. Can you? By contrast, actual decimal arithmetic is not hard to reason about. Additionally, note that this function is inherently incapable of returning 1.04 for example, you can get a number that is printed as 1.04 but it will be 1.04000000000000003552713678800500929355621337890625 (depending on the context in which that value is used, that may or may not matter) | |
Aug 21, 2023 at 21:06 | answer | added | J_H | timeline score: 3 | |
Aug 21, 2023 at 20:42 | comment | added | Sébastien Josserand | Why wouldn't it be reliable? It solves the previous examples | |
Aug 21, 2023 at 20:33 | comment | added | user555045 | Doing things like this is more a sign that you need to implement actual decimal arithmetic, hacking floats this way is not reliable. | |
S Aug 21, 2023 at 20:13 | review | First questions | |||
Aug 21, 2023 at 20:24 | |||||
S Aug 21, 2023 at 20:13 | history | asked | Sébastien Josserand | CC BY-SA 4.0 |