summaryrefslogtreecommitdiff
path: root/Userland/Applications/Calculator/KeypadValue.cpp
diff options
context:
space:
mode:
authorcreator1creeper1 <creator1creeper1@airmail.cc>2021-12-19 19:07:53 +0100
committerBrian Gianforcaro <b.gianfo@gmail.com>2021-12-21 13:22:12 -0800
commitcacac7927b714efa8d0881debb85403baac2e650 (patch)
treece532c2ddd30d624d18d843c433c467f315df792 /Userland/Applications/Calculator/KeypadValue.cpp
parent7ea3d40e1905451da528294e248b8f20e43f0d5f (diff)
downloadserenity-cacac7927b714efa8d0881debb85403baac2e650.zip
Calculator: Construct KeypadValue precisely from the Clipboard contents
Previously, we would use lossy strtod() conversion. This was bad, especially since we switched from internally storing Calculator state in a double to storing it in the KeypadValue class some time ago. This commit adds a constructor for the KeypadValue class that is not lossy by using strtoll(). It handles numbers with and without decimal points as well as negative numbers correctly.
Diffstat (limited to 'Userland/Applications/Calculator/KeypadValue.cpp')
-rw-r--r--Userland/Applications/Calculator/KeypadValue.cpp19
1 files changed, 19 insertions, 0 deletions
diff --git a/Userland/Applications/Calculator/KeypadValue.cpp b/Userland/Applications/Calculator/KeypadValue.cpp
index b677943515..44aaf97654 100644
--- a/Userland/Applications/Calculator/KeypadValue.cpp
+++ b/Userland/Applications/Calculator/KeypadValue.cpp
@@ -19,6 +19,25 @@ KeypadValue::KeypadValue(i64 value)
{
}
+KeypadValue::KeypadValue(StringView sv)
+{
+ String str = sv.to_string(); //TODO: Once we have a StringView equivalent for this C API, we won't need to create a copy for this anymore.
+ size_t first_index = 0;
+ char* dot_ptr;
+ i64 int_part = strtoll(&str[first_index], &dot_ptr, 10);
+ size_t dot_index = dot_ptr - str.characters();
+ if ((dot_index < str.length()) && (str[dot_index] == '.')) {
+ size_t second_index = dot_index + 1;
+ char* end_ptr;
+ i64 frac_part = strtoll(&str[second_index], &end_ptr, 10);
+ size_t end_index = end_ptr - str.characters();
+ u8 frac_length = end_index - second_index;
+ *this = KeypadValue { int_part } + KeypadValue { frac_part, frac_length };
+ } else {
+ *this = KeypadValue { int_part };
+ }
+};
+
KeypadValue KeypadValue::operator+(KeypadValue const& rhs)
{
return operator_helper<KeypadValue>(*this, rhs, [](KeypadValue const&, KeypadValue const& more_decimal_places, i64 less_decimal_places_equalized, i64 more_decimal_places_equalized, bool) -> KeypadValue {