C++ Builder

La Isla Bonita



FloatToStr Function
FloatToStr Function


Description

The FloatToStr() function is defined as:

  extern PACKAGE AnsiString __fastcall FloatToStr(Extended Value);

The function name is unfortunate since it actually takes an Extended parameter which is equivalent to a long double in C++.

Because float data types have only 7-digits of accuracy ("precision") while long double data types have 18-digits of accuracy, we might get results that we don't expect when converting a float number into an AnsiString via FloatToStr().

For example, if we convert the float number 1.6 into a AnsiString through this function, we'll get the following result:

"1.60000002384186"      //AnsiString
The reason is that the decimal information about our 1.6 number provided by our float variable has only 7-digits of precision which is not accurate enough to account for the 8th decimal digit onwards, expected by long double types.

Thus, only the first seven characters (that represent 7 decimal digits) after the point are accurate. So that, the sub-AnsiString "1.6000000" would be accurate while the result: "1.60000002384186" is not.

Conclusion

This function produces accurate results when the values passed on to this function are long double types.

If we want to convert float values into AnsiStrings without having these accuracy problems, we could use the FloatToStrF() function instead. This function lets you specify format, precision, and digits.

Files

FloatToStr.cpp

#include <vcl.h>
#pragma hdrstop

#include "FloatToStr.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
        : TForm(Owner)
{
}
//---------------------------------------------------------------------------

void __fastcall TForm1::Button1Click(TObject *Sender)
{
   //float provides 7-digit precision
   float f = 1.6;

   // Extended (equivalent to the long double C++ data type)
   // provides 18-digit precision
   // Extended range: 	3.6 x 10^–4951 .. 1.1 x 10^4932
   // Extended representation: 80-bit floating point number.
   Extended ex    = 1.6;
   long double ld = 1.6;

   ShowMessage(FloatToStr(f));    //innaccurate after the 7th decimal place
   ShowMessage(FloatToStr(ex));   //accurate
   ShowMessage(FloatToStr(ld));   //accurate
}


Homepage

Copyright © 1997-2003 Rodolfo A. Frino. All rights reserved.