|
@@ -68,11 +68,14 @@ KeypadValue Calculator::begin_operation(Operation operation, KeypadValue argumen
|
|
|
res = argument;
|
|
|
break;
|
|
|
case Operation::MemAdd:
|
|
|
- m_mem = m_mem + argument; //avoids the need for operator+=()
|
|
|
+ m_mem = m_mem + argument; // avoids the need for operator+=()
|
|
|
res = m_mem;
|
|
|
break;
|
|
|
}
|
|
|
|
|
|
+ if (should_be_rounded(res))
|
|
|
+ round(res);
|
|
|
+
|
|
|
return res;
|
|
|
}
|
|
|
|
|
@@ -112,6 +115,9 @@ KeypadValue Calculator::finish_operation(KeypadValue argument)
|
|
|
VERIFY_NOT_REACHED();
|
|
|
}
|
|
|
|
|
|
+ if (should_be_rounded(res))
|
|
|
+ round(res);
|
|
|
+
|
|
|
clear_operation();
|
|
|
return res;
|
|
|
}
|
|
@@ -122,3 +128,29 @@ void Calculator::clear_operation()
|
|
|
m_saved_argument = 0;
|
|
|
clear_error();
|
|
|
}
|
|
|
+
|
|
|
+bool Calculator::should_be_rounded(KeypadValue value)
|
|
|
+{
|
|
|
+ // We check if pow(10, value.m_decimal_places) overflow.
|
|
|
+ // If it does, the value can't be displayed (and provoke a division by zero), see Keypad::set_value()
|
|
|
+ // For u64, the threshold is 19
|
|
|
+ return value.m_decimal_places > rounding_threshold;
|
|
|
+}
|
|
|
+
|
|
|
+void Calculator::round(KeypadValue& value)
|
|
|
+{
|
|
|
+ while (value.m_decimal_places > rounding_threshold) {
|
|
|
+ bool const need_increment = value.m_value % 10 > 4;
|
|
|
+
|
|
|
+ value.m_value /= 10;
|
|
|
+ if (need_increment)
|
|
|
+ value.m_value++;
|
|
|
+
|
|
|
+ value.m_decimal_places--;
|
|
|
+
|
|
|
+ if (value.m_value == 0) {
|
|
|
+ value = 0;
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ }
|
|
|
+}
|