How do I enter fractions in Delphi?

delphi, delphi-2010

Solution

You can do simply

function FractionToFloat(const S: string): real;
var
  BarPos: integer;
  numStr, denomStr: string;
  num, denom: real;
begin
  BarPos := Pos('/', S);
  if BarPos = 0 then
    Exit(StrToFloat(S));
  numStr := Trim(Copy(S, 1, BarPos - 1));
  denomStr := Trim(Copy(S, BarPos + 1, Length(S)));
  num := StrToFloat(numStr);
  denom := StrToFloat(denomStr);
  result := num/denom;
end;

This will accept input of the form examplified by `3/7` and `-4 / 91.5`.

To allow an integer part, add

function FullFractionToFloat(S: string): real;
var
  SpPos: integer;
  intStr: string;
  frStr: string;
  int: real;
  fr: real;
begin
  S := Trim(S);
  SpPos := Pos(' ', S);
  if SpPos = 0 then
    Exit(FractionToFloat(S));
  intStr := Trim(Copy(S, 1, SpPos - 1));
  frStr := Trim(Copy(S, SpPos + 1, Length(S)));
  int := StrToFloat(intStr);
  fr := FractionToFloat(frStr);
  result := int + fr;
end;   

This will in addition accept input of the form examplified by `1 1/2`.

Problem

I have an application which will use measurements, specifically down to 1/16 of an inch. I would really like a convenient way for an end user to enter a value INCLUDING a fractional part, for example, 3 7/16. I realize that I can require the user to just enter decimal values (i.e. 3.1875), but I would really like a better way. Does anyone know of a drop down or spin control that makes this easy to enter? (ideally a DB version of the control.)

Original source