Formatted Numeric Output
May 18, 2012
It is often necessary for programs to produce numeric output in various formats, and most languages provide libraries for this purpose; for instance, C provides the printf
function, which includes the d
and f
format specifications for decimal numbers (integers) and floating point numbers, respectively.
Your task is to write library functions that format integers and floating point numbers; you may follow the formatting conventions of C, or those of some other language, or invent your own. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
This may not conform exactly with the proposed problem, but an interesting read regarding implementing printf for C++ programmers:
http://insanecoding.blogspot.com/2010/03/c-201x-variadic-templates.html
I thought it would be fun to implement the Dartmouth BASIC printing format. This was back in the days where formatting didn’t seem all the necessary as the computer printed how users intuitively expected things to go. In FORTH since that language (a) has a standard word to pick apart a floating point number and (b) default printing is rather unfriendly in that language.
Some tests: