Skip to content

Commit 6cb127d

Browse files
authored
Merge pull request #2222 from pie-framework/fix/PIE-434
fix(charting): avoid floating-point precision errors in the % operator PIE-434
2 parents 13d69db + d325882 commit 6cb127d

1 file changed

Lines changed: 15 additions & 3 deletions

File tree

packages/charting/src/grid.jsx

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,10 +26,22 @@ export class Grid extends React.Component {
2626
const { scale = {}, size = {}, range = {} } = graphProps || {};
2727
const { step = 0, labelStep = 0 } = range;
2828
const highlightNonLabel = step && labelStep && step < labelStep;
29-
// if highlightNonLabel is true, we need to separate the unlabled lines in order to render them in a different color
29+
30+
// Avoid floating-point precision errors in the % operator.
31+
// e.g. 0.6 % 0.2 = 0.19999999999999996, but safeModulo(0.6, 0.2) = 0
32+
const safeModulo = (value, step) => {
33+
const valueDecimals = (value.toString().split('.')[1] || '').length;
34+
const stepDecimals =(step.toString().split('.')[1] || '').length
35+
const decimals = Math.max(valueDecimals, stepDecimals);
36+
const factor = Math.pow(10, decimals);
37+
38+
return ((value * factor) % (step * factor)) / factor;
39+
};
40+
41+
// if highlightNonLabel is true, we need to separate the unlabeled lines in order to render them in a different color
3042
const { unlabeledLines, labeledLines } = (rowTickValues || []).reduce(
3143
(acc, value) => {
32-
if (highlightNonLabel && value % labelStep !== 0) {
44+
if (highlightNonLabel && safeModulo(value, labelStep) !== 0) {
3345
acc.unlabeledLines.push(value);
3446
} else {
3547
acc.labeledLines.push(value);
@@ -55,7 +67,7 @@ export class Grid extends React.Component {
5567
width={size.width}
5668
tickValues={labeledLines}
5769
lineStyle={{
58-
stroke: color.visualElementsColors.GRIDLINES_COLOR,
70+
stroke: unlabeledLines.length ? color.visualElementsColors.GRIDLINES_COLOR : color.fadedPrimary(),
5971
strokeWidth: 1,
6072
}}
6173
/>

0 commit comments

Comments
 (0)