]> git.ipfire.org Git - thirdparty/Chart.js.git/commitdiff
Account for floating point error in niceNum helper (#9343)
authorEvert Timberg <evert.timberg+github@gmail.com>
Thu, 1 Jul 2021 19:07:32 +0000 (15:07 -0400)
committerGitHub <noreply@github.com>
Thu, 1 Jul 2021 19:07:32 +0000 (15:07 -0400)
* Account for floating point error in niceNum helper
* Better solution

src/helpers/helpers.math.js
src/scales/scale.linearbase.js
test/fixtures/scale.linear/tick-step-min-max-step-fp.js [new file with mode: 0644]
test/fixtures/scale.linear/tick-step-min-max-step-fp.png [new file with mode: 0644]

index d9e792c08fb3cd7a43fc5d6d6afc509f258a5a37..fea406c0fc67b38de0d6803bcf53f0c23754a77e 100644 (file)
@@ -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;
index 9e53038e394d698c5a218daf11273acf517edc76..cccfa46d4bf604e7a6a5e18643e83e031aac2938 100644 (file)
@@ -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 (file)
index 0000000..00d3f9c
--- /dev/null
@@ -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 (file)
index 0000000..b11e884
Binary files /dev/null and b/test/fixtures/scale.linear/tick-step-min-max-step-fp.png differ