Small Calculator, Three Bugs: Input Parsing, Unit Drift, and Stale Results
A calculator with two inputs and one output is the "hello world" of interactive UI. It is also a small minefield. These are three defects I hit while building bidirectional CPM ↔ CPC conversion, and the fixes are portable to any numeric form. Bug 1: percentage drift The formula is simple once you see it. Cost per thousand impressions, divided by clicks per thousand impressions, gives cost per…
A tiny calculator with just two inputs and one output, the epitome of a "hello world" interaction, can be riddled with bugs. Three specific issues were encountered while developing bidirectional conversion between Cost Per Thousand Impressions (CPM) and Cost Per Click (CPC).
Bug 1: Percentage Drift
The core formula for calculating CPC from CPM and CTR is straightforward: divide CPM by CTR. However, the tricky part lies within the middle term. Click-Through Rate (CTR) is represented as a percentage (e.g., 2 means 2%). This requires treating the CTR as 2% rather than 2 clicks per 1000. To rectify this, the formula should multiply CTR by 10 (since CTR is per hundred impressions and CPM is per thousand). Writing the derivation as a comment beside the constant clarifies this for future developers.
Bug 2: Validation that Permits Empty Fields
The input fields for cost and CTR were validated using Number( ), which defaults to 0 if the input is empty. This design oversight is beneficial only when both fields are mandatory and cannot be zero. However, when optional fields allow zero values, an empty string should not be mistakenly treated as zero. Proper validation checks should be implemented to address this.
Bug 3: Stale Results After Invalid Submission
A common user experience issue arises when submitting a form with invalid data: the old result remains displayed even after an error. For instance, if a user enters valid values, sees a $0.50 result, edits the cost field to an empty value, and then submits, the previous result ($0.50) should not persist on screen. Clearing the result and displaying a clear error message helps maintain consistency between the error state and the displayed result.
These bugs highlight the significance of correct calculations, thorough validation, and maintaining consistency in UI state. Implementing these fixes not only improves the functionality but also enhances the overall user experience of the calculator.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.