Number Input & Display Logic
20 min read
Add Decimal Input
Task
Allow users to create decimal numbers without adding more than one decimal point.
Open
Open:
js/calculator.js
Add an inputDecimal() method inside the Calculator class.
Add the method
inputDecimal() {
if (this.state.waitingForOperand || this.state.justCalculated) {
this.state.current = '0.';
this.state.waitingForOperand = false;
this.state.justCalculated = false;
return;
}
if (!this.state.current.includes('.')) {
this.state.current += '.';
}
}
The includes('.') check prevents values such as 12.3.4.
Starting with 0. also means a decimal can be entered as the first part of a number.
Test
Run:
calculator.clear();
calculator.inputDigit('1');
calculator.inputDecimal();
calculator.inputDigit('5');
calculator.state.current;
You should get:
"1.5"
Now try:
calculator.inputDecimal();
calculator.state.current;
The value should still be:
"1.5"
Checkpoint
The calculator can now build valid decimal numbers while preventing duplicate decimal points.