How To Force The Correct Decimal Separator

Some English speaking countries use the “point” as decimal separator,
while the rest of the world is using the “comma”. How can you make sure
that the user will press the correct key when entering a number with a
decimal fraction? With the code in this examples, it doesn’t matter!

// Correct the decimal separator

procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char);
begin
  // Delphi automatically sets DecimalSeparator (a global
  // variable) to Windows’ decimal separator
  if Key in [‘.’, ‘,’] then
    Key :=  DecimalSeparator;
end;

// This is a more complete procedure:
// it allows only valid numbers and
// it corrects the decimal separator.
// For educational purposes 😎 
// the code is very detailed.

procedure TForm1.Edit2KeyPress(Sender: TObject; var Key: Char);
type
  TErrNum = (eNone, eInvalidKey, eTooManySeps, eTooManySigns, eSignPos);
const
  ErrMessages : array[eInvalidKey..eSignPos] of string = (
    ‘Invalid key’,
    ‘Only one decimal separator is allowed’,
    ‘Only one sign is allowed’,
    ‘A sign is only allowed in the first position’);
  Signs = [‘+’, ‘-‘];
  Nums = [‘0’..’9′];
  DecSeps = [‘.’, ‘,’];
  Backspace = [#8];
  ValidKeys = Signs + Nums + DecSeps + Backspace;
var
  ErrNum: TErrNum;
begin
  ErrNum := eNone;
  if not (Key in ValidKeys) then
    ErrNum := eInvalidKey
  else if Key in DecSeps then begin
    Key := DecimalSeparator;
    if Pos(Key, Edit2.Text) > 0 then
      ErrNum := eTooManySeps;
  end
  else if Key in Signs then begin
    if Pos(‘+’, Edit2.Text) + Pos(‘-‘, Edit2.Text) > 0 then
      ErrNum := eTooManySigns
    else if Edit2.SelStart <> 0 then
      ErrNum := eSignPos;
  end;
  if ErrNum <> eNone then begin
    Key := #0; // nothing is passed to the Edit
    MessageDlg(ErrMessages[ErrNum], mtWarning, [mbOk], 0);
  end;
end;

Leave a Reply

Your email address will not be published. Required fields are marked *