Skip to content

Commit d1342d0

Browse files
committed
generic: menu spinbox fix floating point error
Signed-off-by: IonutMuthi <[email protected]>
1 parent b1204a2 commit d1342d0

File tree

1 file changed

+13
-6
lines changed

1 file changed

+13
-6
lines changed

gui/include/gui/widgets/menuspinbox.h

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,13 @@ class SCOPY_GUI_EXPORT IncrementStrategy
4545
virtual double increment(double val) = 0;
4646
virtual double decrement(double val) = 0;
4747
virtual void setScale(double scale) = 0;
48+
49+
protected:
50+
static double roundToNDecimals(double value, int n)
51+
{
52+
double factor = std::pow(10.0, n);
53+
return std::round(value * factor) / factor;
54+
}
4855
};
4956

5057
class SCOPY_GUI_EXPORT IncrementStrategy125 : public IncrementStrategy
@@ -55,8 +62,8 @@ class SCOPY_GUI_EXPORT IncrementStrategy125 : public IncrementStrategy
5562
IncrementStrategy125()
5663
: m_steps(1e-9, 1e9, 10){};
5764
~IncrementStrategy125(){};
58-
virtual double increment(double val) override { return m_steps.getNumberAfter(val); }
59-
virtual double decrement(double val) override { return m_steps.getNumberBefore(val); }
65+
virtual double increment(double val) override { return roundToNDecimals(m_steps.getNumberAfter(val), 9); }
66+
virtual double decrement(double val) override { return roundToNDecimals(m_steps.getNumberBefore(val), 9); }
6067

6168
double m_scale;
6269
void setScale(double scale) override { m_scale = scale; }
@@ -83,7 +90,7 @@ class SCOPY_GUI_EXPORT IncrementStrategyPower2 : public IncrementStrategy
8390
while(val > m_steps[i]) {
8491
i++;
8592
}
86-
return m_steps[i];
93+
return roundToNDecimals(m_steps[i], 9);
8794
}
8895
virtual double decrement(double val) override
8996
{
@@ -92,7 +99,7 @@ class SCOPY_GUI_EXPORT IncrementStrategyPower2 : public IncrementStrategy
9299
while(val < m_steps[i]) {
93100
i--;
94101
}
95-
return m_steps[i];
102+
return roundToNDecimals(m_steps[i], 9);
96103
}
97104
double m_scale;
98105

@@ -110,12 +117,12 @@ class SCOPY_GUI_EXPORT IncrementStrategyFixed : public IncrementStrategy
110117
virtual double increment(double val) override
111118
{
112119
val = val + m_k * m_scale;
113-
return val;
120+
return roundToNDecimals(val, 9);
114121
}
115122
virtual double decrement(double val) override
116123
{
117124
val = val - m_k * m_scale;
118-
return val;
125+
return roundToNDecimals(val, 9);
119126
}
120127
void setK(double val) { m_k = val; }
121128
double k() { return m_k; }

0 commit comments

Comments
 (0)