Skip to content

Commit

Permalink
Account for floating point error in niceNum helper (#9343)
Browse files Browse the repository at this point in the history
* Account for floating point error in niceNum helper
* Better solution
  • Loading branch information
etimberg committed Jul 1, 2021
1 parent 3934935 commit fea3f20
Show file tree
Hide file tree
Showing 4 changed files with 28 additions and 1 deletion.
2 changes: 2 additions & 0 deletions src/helpers/helpers.math.js
Expand Up @@ -22,6 +22,8 @@ export const sign = Math.sign;
* @return {number}
*/
export function niceNum(range) {
const roundedRange = Math.round(range);
range = almostEquals(range, roundedRange, range / 1000) ? roundedRange : range;
const niceRange = Math.pow(10, Math.floor(log10(range)));
const fraction = range / niceRange;
const niceFraction = fraction <= 1 ? 1 : fraction <= 2 ? 2 : fraction <= 5 ? 5 : 10;
Expand Down
3 changes: 2 additions & 1 deletion src/scales/scale.linearbase.js
Expand Up @@ -70,7 +70,8 @@ function generateTicks(generationOptions, dataRange) {
// Case 1: If min, max and stepSize are set and they make an evenly spaced scale use it.
// spacing = step;
// numSpaces = (max - min) / spacing;
numSpaces = Math.min((max - min) / spacing, maxTicks);
// Note that we round here to handle the case where almostWhole translated an FP error
numSpaces = Math.round(Math.min((max - min) / spacing, maxTicks));
spacing = (max - min) / numSpaces;
niceMin = min;
niceMax = max;
Expand Down
24 changes: 24 additions & 0 deletions test/fixtures/scale.linear/tick-step-min-max-step-fp.js
@@ -0,0 +1,24 @@
module.exports = {
description: 'https://github.com/chartjs/Chart.js/issues/9334',
config: {
type: 'line',
options: {
scales: {
y: {
display: false,
},
x: {
type: 'linear',
min: 7.2,
max: 21.6,
ticks: {
stepSize: 1.8
}
},
}
}
},
options: {
spriteText: true
}
};
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit fea3f20

Please sign in to comment.