Calculator Controls
25 min read
Add Percentage and Sign Toggle
Task
Implement two controls that transform the current number: percentage and sign toggle.
Open
Open:
js/calculator.js
Add these methods to the Calculator class.
percentage() {
const value = Number(this.state.current);
if (!Number.isFinite(value)) {
return;
}
this.state.current = String(value / 100);
}
toggleSign() {
const value = Number(this.state.current);
if (!Number.isFinite(value) || value === 0) {
return;
}
this.state.current = String(value * -1);
}
Then connect the controls in js/ui.js:
if (action === 'percentage') {
calculator.percentage();
}
if (action === 'sign') {
calculator.toggleSign();
}
Finish by updating the display:
updateDisplay();
Test
Test percentage:
- Enter
50. - Press
%. - Confirm the display shows
0.5.
Test sign:
- Enter
25. - Press
±. - Confirm the display shows
-25. - Press
±again. - Confirm it returns to
25.
Also test 0 with the sign toggle. It should remain 0.
Checkpoint
The calculator now supports percentage and positive/negative transformations without putting that logic inside the DOM event handlers.