Reputation: 3023
I have this component that takes values not neccesarily rounded to the nearest 1000 as an input, like this (see min, max):
...
scale: {
majorUnit: 500,
minorUnit: 100,
min: nearest(minTensionRange, 1000),
max: nearest(maxTensionRange, 1000),
labels: {
template: function (e) {
return getTensionLabel(e, nearest(maxTensionRange, 1000), nearest(minTensionRange, 1000));
}
},
...
});
The nearest function does the following:
function nearest(n, v) {
n = n / v;
n = Math.round(n) * v;
console.log(n);
return n;
}
Works well, until I get a value less than 0.5 or a negative number, in which case it returns 0. What I'm trying to accomplish is feeding the max value of my component with a a positive number rounded up to the nearest 1000 and the min value with a negative number rounded up to the nearest 1000.
I.e:
...
scale: {
majorUnit: 500,
minorUnit: 100,
min: 5000,
max: -5000,
labels: {
template: function (e) {
return getTensionLabel(e, nearest(maxTensionRange, 1000), nearest(minTensionRange, 1000));
}
},
...
});
Upvotes: 2
Views: 3842
Reputation: 4841
If I got it right, you would like to get the nearest 1000 in each case, so you would always like to round the number up in positive case and down in negative case. Try the following:
function nearest(n, v) {
n = n / v;
n = (n < 0 ? Math.floor(n) : Math.ceil(n)) * v;
return n;
}
Upvotes: 5