Representing Values with Units
Keep the scale attached to a value so conversions happen once, at a documented interface.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Convert before comparing
A 1500-millisecond delay and a two-second cap occupy different scales. Convert to 1.5 and 2 seconds before testing the cap. Unit-aware names make this explicit when passing raw numeric values.
Check operation boundaries
For 1500 milliseconds, integer truncation to seconds returns one and discards half a second. A whole-second timeout that must cover the full requested duration can round up to two. The rounding rule is part of the interface and deserves tests for both exact and fractional values.[1][2]
Write a trace with one physical quantity
A navigation state can report distance as 1.2 kilometers while a rate function expects meters per second from elapsed seconds. Convert 1.2 kilometers to 1200 meters before dividing by a duration. At 60 seconds the speed is 20 meters per second. For a sample beginning with meters already, avoid applying the conversion again. Document whether a field name includes the unit or a separate representation carries it. Intermediate names with units make it clearer which side of the transformation a value is on.
Test inputs where a hidden scale would stay invisible
A zero-distance test produces zero under multiple plausible scales. A conversion of 1200 milliseconds to 1.2 seconds reveals both a wrong scale and an unwanted truncation. Comparing positions can require matching both unit and coordinate frame, even if they have the same physical dimension. See local and world coordinates.
When serializing a measurement, carry the required unit or name it in the schema. Review rounded display output separately from stored arithmetic. A test can change the unit and check the expected numerical factor while preserving the underlying quantity.