Binary-decimal conversion

You might already have used forms of the Standard C runtime functions printf and scanf to perform conversion between binary and decimal forms of floating-point numbers. In the CommonPoint application system, these operations fall naturally into the realm of general text formatting. Although "Text Scanning and Formatting" in Application Services discusses this subject in its greater context, this example illustrates some interesting details:

      void IOSampler() {
          TFloatingPointNumberFormatter formatter;
          TStandardText numString;
          TNumberFormatResult resultCode;
      
          formatter.SetMaxFractionDigits(9);
          formatter.SetNanSign("NAN");
          formatter.Format(TFormatableNumber((float) (1.0 / 3.0)), numString, resultCode);
              // numString gets "0.333333343"
          formatter.Format(TFormatableNumber(0.0 / 0.0), numString, resultCode);
              // numString gets "NAN"
          formatter.Format(TFormatableNumber(-kInfinity), numString, resultCode);
              // numString gets "-INFINITY"
      }
This sample gives just a glimpse of what a number formatter can do. Because you determine the strings for infinities and NaNs in software, you can write programs that read and write other programs, including the full range of floating-point constants. The method Scan, which reads decimal strings, also provides range and precision checks; use it to accept user input interactively.

NOTE The nine-digit display of the float value 1/3, with its 4 in the eighth place, is dubious at first glance. But the nine-digit decimal values are so dense in the neighborhood of 1/3 that when 1/3 is rounded to the nearest float value, the rounding error in binary floating-point arithmetic leaps across 10 nine-digit decimal fractions. It is worthwhile to display nine digits of precision, because elsewhere on the number line the nine-digit decimal values are sparse enough relative to float values that eight-digit numbers would not suffice to distinguish float values.


[Contents] [Previous] [Next]
Click the icon to mail questions or corrections about this material to Taligent personnel.
Copyright©1995 Taligent,Inc. All rights reserved.

Generated with WebMaker