Sorting not correct when using toFixed
gsolem opened this issue · comments
Sort by is not sorting as expected. E.g. below list is set to sort by third column - changePercent-
but as you can see it is not working out very well.
Aksje | Last | Change % | Last updated |
---|---|---|---|
KID | 74.60 | 4.48 % | 8/3/2020, 9:49:39 PM |
MOWI | 169.95 | 3.75 % | 8/3/2020, 9:59:04 PM |
GSF | 94.00 | 2.17 % | 8/3/2020, 9:58:57 PM |
TOM | 381.00 | 2.06 % | 8/3/2020, 9:59:05 PM |
ENDUR | 1.52 | 14.72 % | 8/3/2020, 9:52:41 PM |
VEI | 125.60 | 1.95 % | 8/3/2020, 9:50:36 PM |
STB | 50.02 | 1.21 % | 8/3/2020, 9:58:21 PM |
AKER | 386.20 | 0.94 % | 8/3/2020, 9:58:48 PM |
NEL | 18.74 | 0.40 % | 8/3/2020, 9:59:04 PM |
ASA | 114.00 | -1.30 % | 8/3/2020, 9:38:34 PM |
HEX | 46.82 | -1.10 % | 8/3/2020, 9:55:56 PM |
NSKOG | 28.00 | -0.36 % | 8/3/2020, 9:59:12 PM |
Above is when using the modify to round to a fixed nos. of decimals, e.g. modify: parseFloat(x).toFixed(2)
. Without using modify on the column, it is sorting just fine:
Aksje | Last | Change % | Last updated |
---|---|---|---|
ENDUR | 1.52 | 14.72 % | 8/3/2020, 9:52:41 PM |
KID | 74.60 | 4.48 % | 8/3/2020, 9:49:39 PM |
MOWI | 169.95 | 3.75 % | 8/3/2020, 9:59:04 PM |
GSF | 94.00 | 2.17 % | 8/3/2020, 9:58:57 PM |
TOM | 381.00 | 2.06 % | 8/3/2020, 9:59:05 PM |
VEI | 125.60 | 1.95 % | 8/3/2020, 9:50:36 PM |
STB | 50.02 | 1.21 % | 8/3/2020, 9:58:21 PM |
AKER | 386.20 | 0.94 % | 8/3/2020, 9:58:48 PM |
NEL | 18.74 | 0.4 % | 8/3/2020, 9:59:04 PM |
NSKOG | 28.00 | -0.36 % | 8/3/2020, 9:59:12 PM |
HEX | 46.82 | -1.1 % | 8/3/2020, 9:55:56 PM |
ASA | 114.00 | -1.3 % | 8/3/2020, 9:38:34 PM |
From here this looks like expected behavior, at least the js-part of me. .toFixed()
does a string conversion, means sorting will happen from left to right and this is exactly what you can tell from the 1st picture: the leftmost digit is properly sorted. Type inference is somewhat special in js, at least from what I can judge, see this example:
>> x = 500
500
>> y = "1000"
"1000"
>> x < y
true
>> xx = parseFloat(x).toFixed(2)
"500.00"
>> yy = parseFloat(y).toFixed(2)
"1000.00"
>> xx < yy
false
I have no idea what the actual best practice would be in js, but for me the following just works (and another solution would be just call parseFloat()
again on the toFixed()
result --- not really nice, but does the job):
>> x = 123.54446
123.54446 // we want this to show as "123.54" while being sortable
>> xx = Math.round(x*100) / 100
123.54
>> xx = parseFloat(parseFloat(x).toFixed(2))
123.54
So something like this inside your modify:
. But keep in mind that that if the last digit is a zero, then the digit will not be shown, so sometimes it does not look as pretty as it could.