Urgent.News

What's breaking now, across thousands of outlets.

Tech

Testing a small cost calculator: decimal inputs, units, and rounding

A calculator can have a correct multiplication and still give misleading results. A parser might silently accept a unit suffix, a percentage might be interpreted on the wrong scale, or an intermediate value might be rounded before the final total. This tutorial builds a small JavaScript charging-cost example with three separate responsibilities: validate text, calculate with explicit units, and…

A small JavaScript calculator can validate input, perform precise calculations with explicit units, and format results. Prices and energy consumption serve as test cases. The inputs include distance in kilometers, consumption in kWh per 100 kilometers, a home share percentage, two prices in EUR per kWh, and a 10% energy markup expressed in percent.

The home share applies to energy, not session count. The energy markup means multiplying baseline energy by 1.10. The model calculates base kWh, billed kWh, weighted EUR per kWh, and total cost in EUR. For the given example of 1,000 km, 18 kWh/100 km, 60% home energy, prices of EUR 0.32/kWh at home and EUR 0.59/kWh publicly, and a 10% markup, the decimal arithmetic yields a cost of EUR 84.74.

The input grammar accepts unsigned integers with optional decimal points, rejecting whitespace, grouping separators, exponent notation, signs, unit suffixes, leading zeros, and incomplete decimals. Validation consists of two stages: a regular expression check and conversion to a number. The estimate function takes input strings and returns an object with calculated values.

The calculator.mjs file is self-contained, with no external packages. The final result is displayed as EUR 84.74, rounded to two decimal places.

Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.

Read the original at dev.to →

More in Tech

I re-verified 30 disclosed Supabase keys. 20% were still live.

I re-verified 30 disclosed Supabase keys. 20% were still live. The uncomfortable finding: developers who thank you for reporting a leaked key — and swear they rotated it — often don't.

  • Cenk Kurtoglu disclosed 30 Supabase servicerole keys
  • 20% of keys were still live after initial disclosure
  • Kurtoglu offers key rotation verification service

More from Wednesday 21 October →