- Home /
Javascript List, Sort a floating point number? [Solved]
So I've found a bug in my code which I didn't see at first, but it's there and I need to fix it. I have a racing game and I want to sort the scores by Minutes, Seconds, Milliseconds. Scores are saved as floats and then converted to a string that shows MM:SS:MMM
I save all the scores in to a list, which I then try to sort using this function:
var HighScores = new List.<float>();
function sortScore(a : float, b : float){
return a - b;
}
This works perfectly fine, until a score is very close to another score, the sort function doesn't sort anything after the decimal in the floating point number. The scores get screwed up if they're too close together. For example something like this first place 20.001 second place: 30.003 third place 40.033 will sort properly.
But something like this: First place 30.001 Second Place 30.384 third place 31.988 will screw up the sorting, the larger of the two scores, 30.384 will be first, 30.001 will be second, and 31.988 will show as 3rd.
I read that JavaScript will treat numbers as strings when sorting. A suggestion was to build a custom sort function which I did; Here's how I sort the list:
HighScores.Sort(sortScore());
Is there any way to prevent this from happening? My only work around would be to make the predefined scores something like this 31.999 32.999 etc. I'd like to just find a fix for this without having to resort to that, it would look unnatural.
Okay so I solved this on my own, probably could have waited to post this, but I think others might run in to this same issue, lots of developers create racing games so here's the fix:
function sortScore(a : float, b : float){
return a - b;
}
becomes
function sortScore(a : float, b : float){
return (a * 10000) - (b * 10000);
}
it now sorts properly.
Answer by JOHNMCLAY · Aug 23, 2014 at 12:09 AM
Hey Binxalot,
Just stopping by to show my utmost appreciation for posting this. I was in the same hair-pulling, teeth-grindingly frustrating situation until 5 minutes ago...and now, thanks to your simply elegant solution, my teeth remain seated and my hair intact! :D
Thanks a lot! :D
Answer by kendrakelly · Feb 02, 2019 at 09:19 PM
@Binxalot Also just a quick thanks for following up with the solution!! Not working on a game but trying to sort businesses by distances from a current location... this worked wonderfully.
Your answer
Follow this Question
Related Questions
How do I create and loop through a completely generic list in javascript? 1 Answer
merge sort crash Unity 2 Answers
Help with sorting values from a class 2 Answers
Orderby/Sort a List of Lists based on the .Count 1 Answer
Sort() javascript arrays 1 Answer