Home

Number Formatting to Display Decimals

     

Introduction

 

The UnicodeString class is equipped with a method used to format a floating-point number and specify the number of decimal places. Actually, the UnicodeString::sprintf() function imitates the Cís printf() function of displaying strings, integers, and floating variables. In mathematical operations, you can use it to control how to display a decimal number. The syntax of the method is:

System::UnicodeString & __fastcall sprintf(const wchar_t * format);

Following the C system of passing arguments, this member function can at least display a string. Here is an example:

//---------------------------------------------------------------------------
void __fastcall TForm1::Button2Click(TObject *Sender)
{
	Edit2->Text = Edit2->Text.sprintf(L"The best movie of the year");
}
//---------------------------------------------------------------------------

On the other hand, you can use this function to format a floating-point number. In the following example, the values of the dimensions of a sphere are calculated and display in appropriate edit boxes:

//---------------------------------------------------------------------------
void __fastcall TForm1::btnCalculateClick(TObject *Sender)
{
	double Radius, Diameter, Circumference, Area, Volume;
	
	Radius = edtRadius->Text.ToDouble();
	Diameter = Radius * 2;
	Circumference = Radius * 2 * M_PI;
	Area = Radius * Radius * M_PI;
	Volume = Radius * Radius * Radius * 4.00 * M_PI / 3;
	
	edtDiameter->Text = Diameter;
	edtCircumference->Text = Circumference;
	edtArea->Text = Area;
	edtVolume->Text = Volume;
}
//---------------------------------------------------------------------------

Sphere

When the same values are configured using the UnicodeString::sprintf() method, the diameter and the circumference can be set to display two decimal values while the area and the volume display three, as follows:

//---------------------------------------------------------------------------
void __fastcall TForm1::btnCalculateClick(TObject *Sender)
{
	double Radius, Diameter, Circumference, Area, Volume;
	
	Radius = edtRadius->Text.ToDouble();
	Diameter = Radius * 2;
	Circumference = Radius * 2 * M_PI;
	Area = Radius * Radius * M_PI;
	Volume = Radius * Radius * Radius * 4.00 * M_PI / 3;
	
	edtDiameter->Text = edtDiameter->Text.sprintf(L"%.2f", Diameter);
	edtCircumference->Text = edtCircumference->Text.sprintf(L"%.2f", Circumference);
	edtArea->Text = edtArea->Text.sprintf(L"%.3f", Area);
	edtVolume->Text = edtVolume->Text.sprintf(L"%.3f", Volume);
}
//---------------------------------------------------------------------------
 
 
     
 

Home Copyright © 2010-2011 FunctionX, Inc.