Data files · parsing
ASCII to Double: Converting Text to Floating-Point Numbers
Every number that arrives from a text file, a form field, or a command line begins life as a sequence of characters. Converting ASCII to double means reading that sequence and producing the nearest 64-bit floating-point value. The job looks trivial until a file contains a comma as decimal mark, a stray space, or the text 1e400. This page walks through the steps a correct converter takes and the checks a careful script adds around it. It belongs with the other tools in Data and files.
The parsing steps
A converter works left to right. It skips leading whitespace, reads an optional sign, collects the digits before the decimal point, collects the digits after it, and finally looks for an exponent marker (e or E) followed by an optional sign and more digits. Anything left over after that is either trailing whitespace, which is harmless, or garbage, which should be reported.
Take the string -12.5e2. The sign is negative. The integer part is 12 and the fraction is 5, so the mantissa reads 12.5. The exponent is 2. The value is −12.5 × 10² = −1250. Notice that no step needs more than the digit just read and a running total: for each digit d, the accumulator becomes 10 × accumulator + d, and a count of fraction digits is kept so the result can be scaled at the end.
def ascii_to_double(s):
s = s.strip()
if not s:
raise ValueError("empty field")
return float(s) # built-in parser handles sign, point, exponent
print(ascii_to_double("-12.5e2")) # -1250.0
Writing the loop by hand is rarely worth it. Library parsers are tested against thousands of edge cases, and a homemade accumulator that multiplies by 0.1 at each fraction digit drifts by a few units in the last place. Use the built-in routine and spend the effort on what surrounds it.
Why the result is only approximate
A double stores a 53-bit binary significand. The decimal 0.1 has no finite binary expansion, so the parser returns the closest representable value, which is slightly above 0.1. Printing it with 17 significant digits shows the difference. This is not a parsing bug, and the same rounding happens in every language.
Two consequences follow. First, comparing a parsed value with a literal using exact equality is safe only when both went through the same parser. Second, a value written out with at least 17 significant digits and read back returns the identical double, so a text file can serve as a lossless store if the writer is generous with digits.
What goes wrong in real files
Most failures come from the data, not the algorithm. A short list covers nearly all of them:
- A decimal comma, as in 3,14, which many parsers read as a syntax error or, worse, as 3.
- Thousands separators such as 1,234.5.
- Words that mean not-a-number: NA, N/A, null, or an empty field.
- Overflow, where 1e400 is larger than the biggest double (about 1.8 × 10³⁰⁸) and the result is infinity.
- Hidden characters, such as a byte-order mark at the start of a file or a non-breaking space inside a field.
Decide on a policy for each before reading the file. A common choice is to map missing-value words to NaN, reject anything else that fails, and print the line number of the first rejection. Silent conversion of a bad field to zero is the one policy that should be avoided, because it corrupts averages without any sign that something happened.
Converting a whole column
When a file has thousands of rows, convert in bulk and then test the result. Count how many entries are NaN, check the minimum and maximum against what the column should contain, and compare the row count with the line count of the file. Those three numbers catch most mistakes in seconds.
import numpy as np
col = np.array([ascii_to_double(f) for f in fields], dtype=float)
print(np.isnan(col).sum(), col.min(), col.max())
The reverse trip, number to text, has its own pitfalls; see integer to string conversion. Fields that arrive wrapped in quote characters need unquoting first, and spreadsheet exports add their own conventions, covered under reading spreadsheet files into a matrix. Terms such as machine epsilon appear in the glossary.