Allp Raplsf
Allp Raplsf

Reputation: 17

How do you show the decimal places from 0 to how many ever decimals in a float value?

Im working with C, and I am trying to print the values of pi in the format: 3 3.1 3.14 3.145 3.1459 etc. But I am not sure how to do that any hints?

Upvotes: 0

Views: 69

Answers (1)

Eric Postpischil
Eric Postpischil

Reputation: 222660

#include <float.h>  //  For floating-point characteristics, notably DBL_DIG.
#include <stdio.h>


int main(void)
{
    static const double pi = 3.1415926535897932384626433;

    /*  Iterate through number of digits to display, up to number of decimal
        digits that double is guaranteed to preserve through round trip.
        (Note that DBL_DIG is the number of significant digits for that purpose,
        so DBL_DIG-1 is the number after the decimal point given that we have
        one digit, 3, before the decimal point.)
    */
    for (int i = 0; i < DBL_DIG; ++i)

        /*  Print with the number of digits specified in an argument.  An
            asterisk in a format field says to take the number that would be
            there from the parameters, and the number after "." in an "f"
            specification says how many digits to show after the decimal point.
        */
        printf("%.*f\n", i, pi);
}

Output:

3
3.1
3.14
3.142
3.1416
3.14159
3.141593
3.1415927
3.14159265
3.141592654
3.1415926536
3.14159265359
3.141592653590
3.1415926535898
3.14159265358979

Upvotes: 5

Related Questions