Next attempt:
Delphi-Quellcode:
function ToFrac(const AValue: Extended; const ADivisor: Word; const AFrac: Boolean): string;
var
A, B: Integer;
I, F: Extended;
begin
B := ADivisor;
I := Int(AValue);
F := Frac(AValue);
A := Round(F / (1 / B));
if (F = 0) or (A = 0) then
begin
Result := Format('%.0f', [I]);
Exit;
end;
while (A mod 2 = 0) and (B mod 2 = 0) do
begin
A := A div 2;
B := B div 2;
end;
if (A = B) and (A > 0) then
begin
I := I + A;
Result := Format('%.0f', [I])
end
else
Result := Format('%.0f %.0d/%.0d', [I, A, B])
;
if AFrac then
Result := Format('%.0f/%.0d', [(I * B) + A, B])
;
end;
This one allows to get valid value, but need to know divisor. How to compute it? Or maybe there is some existing open sour ce to work with fractions?