Turn float into string

Formatting a floating point number is rather non-trivial. Search e.g. for the Dragon4 algorithm (here is one result).

Very, very naively, you could try this:

  1. Handle NaN and Infinity.

  2. Print the sign (check < 0). Assume henceforth the number is positive real.

  3. If >= 1, truncate and use familiar integer formatting to print the integral part. (There should be a machine instruction for that on any hardware that has a floating point unit.)

  4. Print the decimal separator; now keep multiplying by 10 and print the truncated integral digit.

  5. Stop when you’ve reached the desired precision; think about rounding the last digit correctly.

Leave a Comment