Author: Lou Adler
I would like a TEdit box on my form that only accepts keys to enter a floating
point number that has N number of decimal places. What is the best way to do this?
Answer:
Derive a new component from TEdit and override its KeyPress method. That is fed
characters before the control has inserted them into the text. You can examine the
character, reject it outright if it would not be valid for a floating point number.
If it would be valid you have to examine the content of the edit, the values of
SelStart and SelCount and figure out how the content would look like if you let the
key pass throuogh. Test that new string against what you can accept, if it does not
match you reject the key. The following OnKeyPress handler for a normal tedit
control shows the logic. It should be integrated into a new component which also
would have a property to set the number of allowable decimal digits.
1 2 procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char);
3 const4 MAXNUMBEROFDIGITS = 2;
5 var6 S: string;
7 val: Double;
8 n: Integer;
9 begin10 if key <> #8 then{Always let backspace through}11 if key in ['0'..'9', '-', DecimalSeparator] then12 begin13 {key is a candidate}14 with Sender as TEdit do15 begin16 S := Text;
17 if SelLength > 0 then{key will replace selection}18 Delete(S, SelStart + 1, SelLength);
19 Insert(key, S, SelStart + 1);
20 {S now has string as it would look after key is processed. Check if it is a 21 valid floating point number.}22 try23 val := StrToFloat(S);
24 {OK, it computes. Find the decimal point and count the digits after it.}25 n := Pos(decimalSeparator, S);
26 if n > 0 then27 if (Length(S) - n) > MAXNUMBEROFDIGITS then28 {too many digits, reject key}29 key := #0;
30 except31 {nope, reject key}32 key := #0;
33 end;
34 end;
35 end36 else{key not acceptible}37 key := #0;
38 end;