Search code examples
delphifloating-pointpascalfreepascallazarus

Formatting fraction numbers in Pascal


I need to print values that are in a matrix, these may vary from integer to real. As an example a matrix that my program use, named kernel, is shown below:

kernel[0,0]:= 1/16;
kernel[0,1]:= 2/16;
kernel[0,2]:= 1/16;
kernel[1,0]:= 2/16;
kernel[1,1]:= 4/16;
kernel[1,2]:= 2/16;
kernel[2,0]:= 1/16;
kernel[2,1]:= 2/16;
kernel[2,2]:= 1/16; 

the issue comes when printing each of them, because I couldn't find a way to print a number like 1/16 in a easy-to-read way, the program displays something like 6.2500000000000000000000000000E-2 which is OK but I would prefer to have something more aesthetic like 0.0625 or even better 1/16. Does anyone acknowledge a way of formatting that allows me to do so?


Solution

  • Each array element holds the value of the fraction.

    To write the value as a fraction you can simply calculate the numerator as the product of the array element and the denominator.

    I prefer to use the Format() function for display formatting.

    Given the array you show, two index variables, a and b and the denominator

    denominator := 16;
    for a := 0 to 2 do
      for b := 0 to 2 do
      begin
        s := format('kernel[%d,%d] = %d/%d',[a,b,round(kernel[a,b]*denominator),denominator]);
        memo1.Lines.Add(s);
      end;