Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,885 questions

51,811 answers

573 users

How to convert a decimal value into a fraction (example: 0.5 is 1/2) in Pascal

1 Answer

0 votes
program DecimalToFraction;

const
  Tolerance = 1E-6;
  MaxDenominator = 10000;

type
  Fraction = record
    Numerator: Integer;
    Denominator: Integer;
  end;

function GCD(a, b: Integer): Integer;
begin
  while b <> 0 do
  begin
    a := a mod b;
    a := a + b;
    b := a - b;
    a := a - b;
  end;
  GCD := Abs(a);
end;

function DecimalToFraction(decimal: Real): Fraction;
var
  n, d, bestN, bestD: Integer;
  error, bestError: Real;
begin
  bestN := 1;
  bestD := 1;
  bestError := Abs(decimal - bestN / bestD);

  for d := 1 to MaxDenominator do
  begin
    n := Round(decimal * d);
    error := Abs(decimal - n / d);
    if error < bestError then
    begin
      bestN := n;
      bestD := d;
      bestError := error;
      if bestError < Tolerance then
        Break;
    end;
  end;

  n := bestN;
  d := bestD;
  DecimalToFraction.Numerator := n div GCD(n, d);
  DecimalToFraction.Denominator := d div GCD(n, d);
end;

var
  decimals: array[1..8] of Real = (0.5, 0.3333, 0.25, 0.75, 1.2, -0.4, 3.125, 2.71828);
  i: Integer;
  frac: Fraction;
begin
  Writeln('Decimal to Fraction Conversion:');
  Writeln;

  for i := 1 to 8 do
  begin
    frac := DecimalToFraction(decimals[i]);
    Write('Decimal: ', decimals[i]:0:5, ' -> Fraction: ');
    Writeln(frac.Numerator, '/', frac.Denominator);
  end;
end.



(*
run:

Decimal to Fraction Conversion:

Decimal: 0.50000 -> Fraction: 1/2
Decimal: 0.33330 -> Fraction: 3236/9709
Decimal: 0.25000 -> Fraction: 1/4
Decimal: 0.75000 -> Fraction: 3/4
Decimal: 1.20000 -> Fraction: 6/5
Decimal: -0.40000 -> Fraction: -2/5
Decimal: 3.12500 -> Fraction: 25/8
Decimal: 2.71828 -> Fraction: 1264/465

*)




 



answered Aug 29, 2025 by avibootz
...