blob: 14af87813811d29623edafc3bbbf5aabf9160a3a (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
|
#include "Keypad.h"
#include <AK/StringBuilder.h>
#include <math.h>
Keypad::Keypad()
{
}
Keypad::~Keypad()
{
}
void Keypad::type_digit(int digit)
{
switch (m_state) {
case State::External:
m_state = State::TypingInteger;
m_negative = false;
m_int_value = digit;
m_frac_value = 0;
m_frac_length = 0;
break;
case State::TypingInteger:
ASSERT(m_frac_value == 0);
ASSERT(m_frac_length == 0);
m_int_value *= 10;
m_int_value += digit;
break;
case State::TypingDecimal:
if (m_frac_length > 6)
break;
m_frac_value *= 10;
m_frac_value += digit;
m_frac_length++;
break;
}
}
void Keypad::type_decimal_point()
{
switch (m_state) {
case State::External:
m_negative = false;
m_int_value = 0;
m_frac_value = 0;
m_frac_length = 0;
break;
case State::TypingInteger:
ASSERT(m_frac_value == 0);
ASSERT(m_frac_length == 0);
m_state = State::TypingDecimal;
break;
case State::TypingDecimal:
// Ignore it.
break;
}
}
void Keypad::type_backspace()
{
switch (m_state) {
case State::External:
m_negative = false;
m_int_value = 0;
m_frac_value = 0;
m_frac_length = 0;
break;
case State::TypingDecimal:
if (m_frac_length > 0) {
m_frac_value /= 10;
m_frac_length--;
break;
}
ASSERT(m_frac_value == 0);
m_state = State::TypingInteger;
[[fallthrough]];
case State::TypingInteger:
ASSERT(m_frac_value == 0);
ASSERT(m_frac_length == 0);
m_int_value /= 10;
if (m_int_value == 0)
m_negative = false;
break;
}
}
double Keypad::value() const
{
double res = 0.0;
long frac = m_frac_value;
for (int i = 0; i < m_frac_length; i++) {
int digit = frac % 10;
res += digit;
res /= 10.0;
frac /= 10;
}
res += m_int_value;
if (m_negative)
res = -res;
return res;
}
void Keypad::set_value(double value)
{
m_state = State::External;
if (value < 0.0) {
m_negative = true;
value = -value;
} else
m_negative = false;
m_int_value = value;
value -= m_int_value;
m_frac_value = 0;
m_frac_length = 0;
while (value != 0) {
value *= 10.0;
int digit = value;
m_frac_value *= 10;
m_frac_value += digit;
m_frac_length++;
value -= digit;
if (m_frac_length > 6)
break;
}
}
String Keypad::to_string() const
{
StringBuilder builder;
if (m_negative)
builder.append("-");
builder.appendf("%ld.", m_int_value);
if (m_frac_length > 0)
builder.appendf("%0*ld", m_frac_length, m_frac_value);
return builder.to_string();
}
|