I’m using this function to sort an array of number, some of which are decimals. But in the sort I’m losing the .0 on those values. I’d like to retain this precision when it’s specified, but not add it when it isn’t.
For example: [1.5, 2, 0.75, 1.0, 0.75] should sort to [2, 1.5, 1.0, 0.75] but using the function below it sorts to [2, 1.5, 1, 0.75]
var sortNums = function( arr ) {
// Quit if arr is not an array.
if ( !$.isArray(arr) ) { return false; }
// Sort highest to lowest:
arr.sort(function(a,b) {return (b-a);});
// Remove non-numeric vals and return:
return $.map(arr, function(v) {if (typeof v === 'number') {return v;}});
};
JavaScript removes tailing decimal zeros.
If you want to keep the decimals you need to cast them as strings. And you could then cast them as numbers in the sort process, if needed.