From: Evert Timberg Date: Thu, 1 Jul 2021 19:07:32 +0000 (-0400) Subject: Account for floating point error in niceNum helper (#9343) X-Git-Tag: v3.4.1~4 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=fea3f20762cc62b159f0f716ccd636994ee03b6d;p=thirdparty%2FChart.js.git Account for floating point error in niceNum helper (#9343) * Account for floating point error in niceNum helper * Better solution --- diff --git a/src/helpers/helpers.math.js b/src/helpers/helpers.math.js index d9e792c08..fea406c0f 100644 --- a/src/helpers/helpers.math.js +++ b/src/helpers/helpers.math.js @@ -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; diff --git a/src/scales/scale.linearbase.js b/src/scales/scale.linearbase.js index 9e53038e3..cccfa46d4 100644 --- a/src/scales/scale.linearbase.js +++ b/src/scales/scale.linearbase.js @@ -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; diff --git a/test/fixtures/scale.linear/tick-step-min-max-step-fp.js b/test/fixtures/scale.linear/tick-step-min-max-step-fp.js new file mode 100644 index 000000000..00d3f9c49 --- /dev/null +++ b/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 + } +}; diff --git a/test/fixtures/scale.linear/tick-step-min-max-step-fp.png b/test/fixtures/scale.linear/tick-step-min-max-step-fp.png new file mode 100644 index 000000000..b11e88478 Binary files /dev/null and b/test/fixtures/scale.linear/tick-step-min-max-step-fp.png differ