Programming · free software · the open webSubscribe via RSS

What Is the Risk of Using Floating-Point Values for Identifiers?

From the earlier reference collection. Read the current software blog.

Identifiers label entities; floating-point numbers represent approximate quantities. Using one for the other can change values or their meaning.

Labels are not measurements

An identifier answers “which record?” rather than “how much?” Arithmetic on an ID usually has no useful meaning. Yet if a spreadsheet or parser treats a long identifier as a floating-point number, it may round the value or display it in scientific notation. The resulting value can look plausible while no longer matching the original key.

Leading zeros can also matter. The IDs 0042 and 42 may be distinct strings even though they become the same numeric value. If a system parses both as numbers, it loses the distinction before it can be exported or compared.

Precision can disappear

Floating-point formats cannot represent every possible decimal integer exactly once values grow large enough. A sufficiently long numeric-looking key may therefore be altered when converted to a floating-point value and back to text. This is particularly damaging because the export may not signal that a change occurred.

Consider a data exchange where record IDs are long sequences of digits. If a spreadsheet rounds the final digits, a join against another file may fail or, worse, attach a row to an unintended record. The error is not fixed by increasing the number of displayed decimal places if the underlying value has already changed.

Represent keys as text

Define identifiers as strings, even when they contain only digits. This preserves leading zeros, punctuation, case, and exact characters. Document whether whitespace is significant and whether identifiers are case-sensitive. If the system imposes a numeric-looking format, express that as a validation rule on the string rather than converting it to a quantity.

Keep measurements numeric and keys textual. A field named amount should support arithmetic under a documented unit; a field named account_id should be compared for exact identity. Clear names and data types help prevent software from making an inappropriate conversion.

Test real export paths

Use test identifiers with leading zeros, long digit sequences, and letters if the format permits them. Export and import through the tools your audience is likely to use, then compare the values character for character. Check that joins still match after round-tripping.

If a consumer insists on numeric identifiers, explain the precision and formatting risks and provide a safer interchange path. The reliable default is simple: identifiers are labels, so encode them as text and avoid arithmetic transformations that can silently change which entity they identify.

Suggest a correction · All posts