Search code examples
c++floating-pointieee-754

How to determine the last nonzero decimal digit in a float?


I am writing a float printing and formatting library and want to avoid printing trailing zero digits.

For this I would like to accurately determine the last nonzero digit within the first N decimal places after the decimal point. I wonder whether there is a particular efficient way to do this.


Solution

  • This (non-trivial) problem has been fully solved. The idea is to print exactly enough digits so that if you converted the printed digits back to a floating-point number, you would get exactly the number you started with.

    The relevant paper is "Printing Floating-Point Numbers Quickly and Accurately", by Robert Burger and R. Kent Dybvig. You can download it here.