2

I have to print a floating point value, however the precision is not known at compile time. So this parameter has to be passed as agument. How this can be achieved. In windows, with CString, the format function helps to achieve this. How to achieve this without CString. Code:

int main()
{

   /* This below code segment works fine.*/
   char str[80];
   sprintf(str, "Value of Pi = %.3f", 3.147758);
   std::cout << str << std::endl; //Prints "Value of Pi = 3.148"

   /* When the precision may vary, henc It needs to be printed required on that.*/
   char str2[80];
   std::string temp = "%.3f";   //This is required as the precision may change. 
                                    // i.e I may have 4 instead 3 decimal points.
   sprintf(str2, "Value = %s", temp, 3.148257);
   std::cout << str2 << std::endl;  //Prints "Value = <null>"
   return 0;
}
evilruff
  • 3,849
  • 1
  • 13
  • 27
suma
  • 533
  • 2
  • 6
  • 11

5 Answers5

6

You need the

"%.*f"

syntax, where the "*" refers to the next argument.

This is all documented.

Parker Coates
  • 5,918
  • 2
  • 26
  • 29
user207421
  • 289,834
  • 37
  • 266
  • 440
1

You can use std::stringstream to convert float to std::string. If you want to use sprint. than use * for width. Details here.

Community
  • 1
  • 1
Mohit Jain
  • 29,414
  • 8
  • 65
  • 93
1

If I understand your question right, you can use setPrecision(..) to achieve desired result:

#include <iostream>
#include <iomanip> // for setprecision()
int main()
{
    using namespace std;

    cout << setprecision(16); // show 16 digits
    float fValue = 3.33333333333333333333333333333333333333f;
    cout << fValue << endl;
    double dValue = 3.3333333333333333333333333333333333333;
    cout << dValue << endl;
}
evilruff
  • 3,849
  • 1
  • 13
  • 27
0

If you can use iomanip then do this:

#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
    int numOfDecimals = 2;// this controls precision. change to what ever you want
    float PI = 3.147758;

    cout << fixed << setprecision(numOfDecimals);
    cout << PI << endl;
    return 0;
}
FrostyZombi3
  • 434
  • 3
  • 10
0

if you wanted to find the amount of decimal places on the fly, you could do something like the following which counts the the amount of decimal places. This would mean you do not have to pass in the format string at all.

#include <iostream>
using namespace std;

int main() 
{
double dNum = 3.14159265359, threshold = 0.00000000005;
double temp = dNum;
int count = 0;
while((temp - (int)temp) > threshold) 
{
    temp *= 10;  
    threshold *=10;
    count++;              
} 
char buffer[50];
sprintf(buffer,"value is = %.*f",count,dNum);
return 0;
}
Mike
  • 126
  • 9