2

I have a code where i can get digit upto 9 digits after decimal point so say something like 0.123456789. Now we can have a case where i get the value 10.123 or say 1001.12. Now there are only 3 digits after decimal point and 2 digits in e.g 10.123 and 1001.12. I am using

#include <iostream>
#include <iomanip>
#include <sstream>
#include <stdio.h>

using namespace std;
int main()
{
 std:stringstream ss;
 double val = 1.234;
 ss.str(std::string());
 ss << std::fixed;
 ss << std::setprecision(9);
 ss << val;
 string number= ss.str();
 std::cout << number <<"\n";
 return 0;
}

Above would give output as 1.234000000 . Note that i would want the precision to be handled automatically depending on the length of the digits after decimal point. One way is for me to find number of digits after decimal point and set precision evverytime , is there some other standard method provided, that takes care of it ?

Thanks

Invictus
  • 4,028
  • 10
  • 50
  • 80
  • Do you want to remove trailing zero? This post might help: https://stackoverflow.com/q/11047994/4123703 – Louis Go Aug 12 '20 at 09:40
  • _"One way is for me to find number of digits after decimal point and set precision evverytime"_ then why are you setting the precision? – Alberto Sinigaglia Aug 12 '20 at 09:42
  • 2
    Calculating the number of digits after a decimal point for a floating point type is not a trivial task. At some point, assumptions need to be made which are best conjected from your program context. That's probably why no such function has made it into the standard. – Bathsheba Aug 12 '20 at 09:43
  • Possible duplicate of https://stackoverflow.com/questions/2489627/setting-minimum-number-of-decimal-places-for-stdostream-precision – Jerry Jeremiah Aug 12 '20 at 10:06
  • 2
    Ok, this may not be a good idea but if you really want to do it: `ss << std::setprecision(log10(val)+9) << val;` (It prints the max digits in cases where floating point is inexact) https://godbolt.org/z/8cG6f1 – Jerry Jeremiah Aug 12 '20 at 10:12
  • @JerryJeremiah though this looks good but then it has slight precision loss, i cannot afford that precision loss. Thanks – Invictus Aug 27 '20 at 08:05
  • If you need the complete precision of the value then you can't set the precision because you will lose something. You are the one that was setting the precision to 9 - all I am doing is setting it to 9 plus the length of the part to the left of the decimal. Or did I misunderstand what you were trying to do? – Jerry Jeremiah Aug 27 '20 at 21:36
  • @JerryJeremiah Sorry if i was not clear, I am setting it to 9 because i know my datasource would send max upto 9 digits after the decimal point. – Invictus Aug 30 '20 at 07:43

0 Answers0