2

I try to write a large double number which is the time that takes my function to produce the result into txt file( using c++).

for exemple in my console, the function take 0.000029 (time unit), when i write the value into my txt file it is converted into : 2.9e-05

My question: how can i write the value as it is in the console i.e 0.000029 ?

here is my code: *`

clock_t cPrec1=0;
double duration1 =0.0;
clock_t cTime1;

cTime1 = clock();
bool h= check(4, copy);
duration1 = ( cTime1 - cPrec1 ) / (double) CLOCKS_PER_SEC;
cPrec1 = clock();
outfile << space<< 1 << space << duration1<< space <<'\n'  ; 
printf(" saved\n");
`

Thanks for helping me.

FifaBen
  • 45
  • 4
  • 1
    Does this answer your question? [C++ Walkthrough cout.setf(ios::fixed); and cout.precision();](https://stackoverflow.com/questions/10181149/c-walkthrough-cout-setfiosfixed-and-cout-precision) – Raj Dec 14 '19 at 10:51
  • [How to output float to cout without scientific notation or trailing zeros?](https://stackoverflow.com/q/18881854/995714), [Prevent scientific notation in ostream when using << with double](https://stackoverflow.com/q/2335657/995714), [Turn off scientific notation on float](https://stackoverflow.com/q/6301547/995714) – phuclv Dec 14 '19 at 11:05

2 Answers2

1

Use:

outfile << std::setprecision(7) << duration1
  • Thanks @Juan but it didn't work for me !! the duration still converted in my file `outfile << space<< 1 << space << std::setprecision(5) << duration1<< space <<'\n' ; ` , I'm using C++11 – FifaBen Dec 14 '19 at 10:59
  • 1
    @FifaBen Use `std::fixed` – Raj Dec 14 '19 at 11:00
1

You can use std::setprecision() and std::fixed function.

when you use a stream you can add a "<< std::setprecision(n)" at the beginning ( or even before the double number ) to set how many number after the dot you want to see. The parameter of this function is an integer that specify the number after the dot that are printed.

Another useful function is std::fixed that can be used like the previous on in the stream ( ex. "<< std::fixed" ). I report to you the definition of the function :

When floatfield is set to fixed, floating-point values are written using fixed-point notation: the value is represented with exactly as many digits in the decimal part as specified by the precision field (precision) and with no exponent part.

I leave you also 2 useful links for this function:

std::setprecision

std::fixed

Zig Razor
  • 3,381
  • 2
  • 15
  • 35