Search code examples
floating-pointlanguage-agnostic

Is it possible to print a float using integer arithmetic only?


I'm currently reading about floating point numbers and I've stumbled upon the following exercise:

Print a float in decimal format. The float is assumed to be IEEE 754 single. All the decimal digits must be printed, including those obtained because of rounding errors. For example, when the user inputs 0.1, the corresponding float is shown as 0.1000000015, and so on.

Is it possible not to use floating-point operations to print a float in decimal format? I'm aware of the simplest approach of multiplying repeatedly the float by 10, truncating it and taking the least significant decimal digit in the integer part. But doing so requires floating point multiplication and truncation.

EDIT: my main question is about printing the fractional part. This is what I'm trying to implement.

Step 0. Set:

result = 0
addend = 5

Step 1. Locate the beginning of the fractional part of the float in its binary representation (de-normalization would be done here in calculations by hand).

Step 2. After marking the beginning of the fractional part, read the bits one by one from left to right. Calculate:

if (bit_read = 1)
    result = result * 10 + addend
addend = addend * 5

Repeat step 2 until the fractional part ends.

Step 3. Print the result as integer.

Will such an algorithm work correctly with all the range of normals and denormals?


Solution

  • If you have access to binary representation of your float (in your "agnostic language"), you can read each bit one by one to a string - and then parse that string using only integers (to print it as float).

    So in above case the answer is: Yes

    UPDATE (after question edit)

    May be THIS description of float representation an it parsing will be useful in your case.