|
Technical answers from the trenches |
|
Handling Database Percentages
| ||||
Posted: 9 March 2004 |
||||
  |
Applies to: Delphi 5.0 and later |
|||
  |
Audience: Intermediate |
|||
Question: I'm creating a database application with Delphi and need a way to let my users enter percentage values easily. What can I do?Answer: Use the TField's OnGetText() and OnSetText() events to convert the percentage value as it's being read from and saved to the underlying table, as shown in the following code sample: procedure TForm1.tblItemsDiscountGetText(
Sender: TField; var Text: String; DisplayText: Boolean );
begin
Text := formatFloat( '0.0###%', Sender.AsFloat * 100.0 );
end;
procedure TForm1.tblItemsDiscountSetText(
Sender: TField; const Text: String );
var
dblValue : Double;
strValue : String;
begin
if rightStr( Text, 1 ) = '%' then
strValue := trim( leftStr( Text, length( Text ) - 1 ) )
else
strValue := trim( Text );
dblValue := strToFloat( strValue );
if ( dblValue > 1.0 ) or ( dblValue < 0.01 ) then
dblValue := dblValue / 100.0;
Sender.AsFloat := dblValue;
end;Note: This example assumes you're using Delphi 7 or later. If you're using an older version, you may need to use different functions from the StrUtils or SysUtils units. For more information, search Delphi Help for the "String handling routines" topic. Understanding the ProblemFrom a design perspective, it's natural and appropriate to store percentages as floating point values; that is, a value of 20% is best stored as 0.20. From a user's perspective, however, it can be difficult to remember to mentally convert the percentage to a decimal representation. In this example, OnSetText() automatically converts string percentage values to their decimal equivalents. It does this by:
If your application requires percentages larger than 100%, you'll need to adjust OnSetText() accordingly. This may be more difficult than it seems at first glance; use care to ensure accuracy. The preceding OnGetText() event supports the conversion process by converting the internal value to a percentage and then appending a percentage symbol. This reminds reminds users to enter percentages as numbers, e.g. as 20%, not 0.20. Remember to remove the percentage symbols; otherwise, Delphi raises an EConvertError exception when trying to save the value. Because this code is placed on the field object, no additional code is needed for your data entry forms. By managing the conversion between the value entered by the user and the number actually stored in your database tables, you can create applications that are easier to use. In turn, this ensures your applications will be used more frequently and with less frustration. |
|||
|
||||||||
|
Copyright © 2000-2004, techtricks.com; All Rights Reserved. Acknowledgements, Disclaimers, Terms and Conditions. |
||||||||
|
Article last updated on 18 March 2004
|
||
|
|
||
|
[- End -]
|