0

I am getting an issue when trying to output my float using std::cout <<

I have the following values:

 vector2f = {-32.00234098f, 96.129380f} //takes 2 floats (x, y) output: -32.0023:96.1294 

What I am looking for is:

 output: -32.00234098:96.129380 

The actual numbers could be vary from the 7 decimal places (.0000007) to 3 decimal places (.003) so setting a fixed rounding number does not work in this case.

Any help would be great as I have tried changed to doubles as well but to no avail.

Thanks in advance!

4
  • You need to use the std::fixed output manipulator. (And possibly the std:setprecision() manipulator too.) Commented Oct 21, 2017 at 17:09
  • Even with the fixed it is still rounding the number at the end and can't use the std::setprecision() method Commented Oct 21, 2017 at 17:12
  • 2
    float is only accurate to about 7 decimal digits not 7 decimal places. Your required output is 10 and 8 digits respectively so there will be rounding/inaccuracy. Commented Oct 21, 2017 at 17:15
  • Perhaps use long double, it has more decimal digits than float and double. Commented Jul 29, 2020 at 12:54

2 Answers 2

9

There are 2 problems.

  1. you need to include <iomanip> and use the std::setprecision manipulator.

  2. To get the level of accuracy you want you will need to use doubles rather than floats.

 

e.g.:

#include <iostream> #include <iomanip> int main() { auto x = -32.00234098f, y = 96.129380f; std::cout << std::setprecision(8) << std::fixed << x << ":" << y << std::endl; // doubles auto a = -32.00234098, b = 96.129380; std::cout << std::setprecision(8) << std::fixed << a << ":" << b << std::endl; } 

example output:

-32.00234222:96.12937927 -32.00234098:96.12938000 
Sign up to request clarification or add additional context in comments.

2 Comments

I was wanting to avoid using the <iomanip> header but it appears I need to use it for the case of getting extensive accuracy beyond the decimal point. Thanks!
this example still rounds the decimal part if the precision number is less than the available decimal. Try this for example: double a=2.003943; std::cout << std::setprecision(3) << std::fixed << a << std::endl; outputs 2.004instead of 2.003. But I want is 2.003. Is there any way to achieve this in cpp without implementing the function yourself?
1

You can set the output precision of the stream using std::precision manipulator.

To print trailing zeroes up to the given precision like in your example output, you need to use std::fixed manipulator.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.