在数字排序期间保持精度
我使用这个函数对数字数组进行排序,其中一些是小数。但在这种情况下,我丢失了这些值的 .0
。我想在指定时保留此精度,但在未指定时不添加它。
例如: [1.5, 2, 0.75, 1.0, 0.75]
应排序为 [2, 1.5, 1.0, 0.75]
但使用下面的函数排序为 [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;}});
};
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;}});
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
JavaScript 删除尾随的小数零。
如果你想保留小数,你需要将它们转换为字符串。如果需要的话,您可以在排序过程中将它们转换为数字。
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.
它们本身就没有任何精度。但是
sort
已经可以正常工作,并且借助 JavaScript 无限有用的自动转换,-
可以为您完成这项工作。请参阅:http://jsfiddle.net/hqc33/They don't have any sort of precision to begin with, per se. But
sort
already works properly and with JavaScript's infinitely useful automatic conversions,-
does the work for you. See: http://jsfiddle.net/hqc33/