KeV
KeV

Reputation: 2891

Rounding a float number to 2 decimals to write it to a text file

I am working on a school project and I have to write a float number to a text file. The problem is that i only want to write the float number up to 2 decimals to the file. I searched a lot on the internet but I only found the "setprecision" function for streams.

I can't do that because I don't want to print it but i want to write it to a file with only 2 decimals. So I have to first convert the float number to the same number but with only 2 decimals, then i put it into a string (that already contain other characters). And then I write that string to the output file.

I found in the description of the "ofstream" a method "precision", but I don't think it could work for what I'm trying to do. (http://www.cplusplus.com/reference/fstream/ofstream/)

Does anyone know a function who does that or a manner for doing that?

Thanks for your help!

Upvotes: 1

Views: 4487

Answers (1)

bames53
bames53

Reputation: 88195

I can't do that because I don't want to print it but i want to write it to a file with only 2 decimals.

ostreams aren't just for printing. You can do the same thing with ofstream as you can do with cout.

std::ofstream fout("out.txt");

fout << std::setprecision(2) << 1.23456;

That function makes a string that contains the price with the name of the article and the rest of the information I want. The function returns that string and then I write that string to the output file

Well you could write the output by passing an ostream reference to the function instead of getting a string back. You could also have the function just do the formatting when it writes the float into the string. Ostreams aren't just for printing or writing to files:

std::stringstream ss;

ss << std::setprecision(2) << 1.23456;

std::string s = ss.str();

Upvotes: 3

Related Questions