Parsing 12' 6" and 2.4 m: measurement input that doesn't annoy people
Most online calculators give you a number box and a unit dropdown. Then someone measures their patio with a tape, gets 12 feet 6 inches , and has to work out that that's 12.5 before they can type anything. I build Toggle9 , a set of free calculators, and I wanted the input box to accept what people actually write down. This post walks through the parser behind it: under 200 lines of plain…
The parser behind Toggle9, a set of free calculators, accepts various input formats for measurements and returns consistent values. It handles inputs like "12 6" which represents 12 feet 6 inches, and converts it to 12.5 feet. Additionally, it accepts "12 -6 1/2" which is equivalent to 12.5417 feet, and "12 1/2" or "12½" which also equates to 12.5 feet.
The parser can also process decimal measurements such as "2.4 m", converting it to 7.874 feet when in a feet field. For inputs like "2,5" in a meters field, it converts it to 2.5 meters. The parser supports different decimal and thousands separators, such as "1,250" (which becomes 1250) and "12 + 3 + 6" which converts to 15.5 feet. It also parses expressions like "12 x 10" as an area of 120 square feet and stores it as 120 m².
However, the parser rejects certain invalid inputs with user-friendly error messages. For instance, "12 sq ft in a length field" is flagged as "That looks like an area; this field needs a length." and "12 apples" is rejected with "Try 12.5, 12 1/2 or 12 6."
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.