gargantuan提出了一个问题:How to increase the value of a number to the next multiple of 10, 100, 1000, 10,000 and so on,或许与您遇到的问题类似。
There is no need to go into the land of strings, which could be awkward if you ever had a decimal value.
function RoundedMax(a) {
var mx = Math.max.apply(Math, a);
if (mx == 0) {return 0};
var size = Math.floor(Math.log(Math.abs(mx)) / Math.LN10);
var magnitude = Math.pow(10, size);
var yMax = Math.ceil(mx / magnitude) * magnitude;
return yMax;
}
function RoundedMin(a) {
var mn = Math.min.apply(Math, a);
if (mn == 0) {return 0};
var size = Math.floor(Math.log(Math.abs(mn)) / Math.LN10);
var magnitude = Math.pow(10, size);
var yMin = Math.floor(mn / magnitude) * magnitude;
return yMin;
}
var arr = [-9.9,-1.23,-8.2,-2.01,-4.5,0];
document.write(RoundedMax(arr) + " " + RoundedMin(arr));
Outputs: 0 -10.
EDIT Updated in view of the comments. Now works even in IE8.
希望本文对你有帮助,欢迎支持JavaScript中文网