I want to read floats and doubles from standart input and save its precision (exact the same digits after floating point) and be able to output (cout/printf) as it is. What the most convinient (and simplest way) to do this? Thanks!

  • 1
    Since float/double are not infinite precision, the only way to do this reliably is to read it in as a string and to maintain the original string along with the converted float/double. May 31, 2016 at 17:31
  • It is impossible to do. The reason is obvious - in stdin/stdout floating point numbers are represented as decimal numbers (it is a requirement of standards). C or C++ standards do not specify internal representation of floating point numbers, therefore there cannot be possible to write a portable conversion from string to float/double and backwards. Even used de-facto standard representation of the numbers does not allow decimal to binary reversible conversions in general case. To illustrate: try to convert 1/3 into decimal notation and back, keeping precision. Dec 18, 2017 at 22:29

3 Answers 3

float f;
cin >> f;
cout << f;
  • But with double 12345.56789 the same aproach doesn't work. double d; cin >> d; cout << d;
    – meathme
    May 31, 2016 at 21:54

Use setprecision.

Here is the solution

cout<<setprecision(the precision you want to set here)<<variablename;

eg. If you want to set precision of the output to 5 for variable var use it like this:


setprecision is a manipulator. Learn more about manipulators here.

It sets the decimal precision to be used to

format floating-point values on output operations. Behaves as if member precision were called with n as argument on the stream on which it is inserted/extracted as a manipulator (it can be inserted/extracted on input streams or output streams).

This is a manipulator and is declared in header <iomanip>


Since the input has an unknown precision, the simplest method is to read them as strings, not doubles/floats.

If you need the float value, a simple string to double conversion is needed.

Any other method will probably fail since you rely on imperfect conversion from string to float done by the standard library.

The latter can't distinguish between 0.4 and 0.40.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.