decimalpascalreal-datatype

Counting the number of decimal places in pascal


I just started studying pascal and I have to do a pascal program as homework. I made it but I don't know how to count the number of decimal places in a real number (the number of digit after the ".").

I need it just to format well a real number (like write(real:0:dec) where dec is the number of decimal digit i don't know how to know). I'd like to do that because i don't want it in scientific notation or with many unnecessary zeros.

For example if a real number is 1.51 (x) and I write writeln(x:0:4); or WriteLn(Format('%*.*f', [0, 4, x])); it will show 1.5100 but I want it to be just 1.51; and if the number is like 1.513436, it will show only 1.5134 . So I would make it like writeln(x:0:dec); with something that makes dec the number of decimal digits of x.


Solution

  • The Format() function is normally used in situations like this.

    WriteLn(Format('%*.*f', [0, dec, your_real_number]));
    

    *.* is interpreted as total_characters.decimal_digits. Passing zero for the first means that width is adjusted according to how large your real is. The number of decimals can be a variable (dec), which you can adjust to your specification.


    Update:

    You mention that you want an exact representation of a float with respect to the number of decimals.

    As mentioned in my comment, most floating point values does not have a finite number of decimals. And most decimal fractions cannot be represented by a binary type.

    There are some libraries that can handle floating point values of arbitrary size. See TBigFloat for example. There is a formatting routine that can strip redundant zeroes from a decimal float.


    Still, there is a possibility to remove trailing zeroes by using the general format specifier:

    WriteLn(Format('%g',[your_real_number]));
    

    You can specify the width and the number of significant digits as well.