pHbits
pHbits

Reputation: 386

Print a variable number of digits of a double using printf

Anyone knows if it is possible to use printf to print a VARIABLE number of digits?

The following line of code prints exactly 2:

printf("%.2lf", x);

but let's say I have a variable:

int precision = 2;

Is there a way to use it in printf to specify the number of digits?

Otherwise I will have to write a 'switch' or 'if' structure.

Thanks

Upvotes: 7

Views: 9047

Answers (4)

olevegard
olevegard

Reputation: 5532

If you use C++, you can use setprecision :

#include <iostream>
#include <iomanip>      // std::setprecision

int main () {
    int precision = 2;
    double f =3.14159;

    std::cout << std::setprecision(precision) << f << '\n';
    ++precision;
    std::cout << std::setprecision(precision) << f << '\n';

    return 0;
}

Output :

3.1
3.14

You can read more about it here

Upvotes: 2

MyChaOS
MyChaOS

Reputation: 332

Yes: printf("%*d", width, num): see here: http://linux.die.net/man/3/printf

If you are using C++ you could use std::cout in combiation with ios_base::precision() : http://www.cplusplus.com/reference/ios/ios_base/precision/

Upvotes: 4

AVX
AVX

Reputation: 116

It is possible:

#include <stdio.h>

int main() {
    int precision = 3;
    float b = 6.412355;
    printf("%.*lf\n",precision,b);
    return 0;
}

Upvotes: 10

MD Sayem Ahmed
MD Sayem Ahmed

Reputation: 29166

Yes, you can do that easily -

int precision = 2;
printf("%.*lf", precision, x);

Upvotes: 8

Related Questions