TEdit with negative floats (Ref: TEdit right align and numbers)
"Hawk" asked about limiting a TEdit to just numbers, and I have had
a similar need. The CSpinEdits don't allow decimal points, so my
previous applications have been real kluges.
So based on the thread "TEdit right align and numbers" I solved a
long-standing need and figured I would share it. Sorry, but I haven't
addressed the right-justify part of the question yet.
This allows a TEdit to accept only numbers, but allows editing
using the backspace key along with the arrow keys and cursor.
Also, it allows only a single decimal point and a minus sign at the
front.
Hopefully, this is an idiot-proof way to provide input of numbers
only, including negatives and decimals, so that a FloatToStr call
won't return an error.
If someone wants to validate this and let me know, I would
appreciate it.
void __fastcall TForm1::Edit1KeyPress(TObject *Sender, char &Key)
{
bool minus_OK,period_OK=true;
if(Edit1->Text.Length()>0){
for(int i=1;i<(Edit1->Text.Length()+1);i++){
if(Edit1->Text.SubString(i,1)=="."){
period_OK=false;
break;
}
}
}
if((Edit1->SelStart==0)&&(Edit1->Text.SubString(1,1)!="-")){
minus_OK=true;
}else{
minus_OK=false;
}
if(!((isdigit(Key))||((Key==45)&&minus_OK)||((Key==46)&&period_OK)||(Key==8))){Key=0;} // 45 is a minus, 46 is a period, 8 is a backspace