0

I was trying to set the precision to 6 digits but using setprecision(6) alone doesn't do the trick. Why?

#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
    float num = 1.423;
    cout<<setprecision(6)<<num;
    return 0;
}

It results in 1.423 only rather then 1.423000 until I use fixed

cout<<setprecision(6)<<num;

  • 2
    There's no use of `fixed` in the code you show... – Jesper Juhl Nov 03 '22 at 17:01
  • 1
    Use `std::fixed` if you want the output to be in *fixed format* mode. – Eljay Nov 03 '22 at 17:06
  • @Eljay but why we need to set it to fixed? – Aashish Aggarwal Nov 03 '22 at 17:19
  • You need to use [std::fixed](https://en.cppreference.com/w/cpp/io/manip/fixed) because you want a behavior other than the default. – Retired Ninja Nov 03 '22 at 17:24
  • Set it to `std::fixed` to get fixed formatting. Set it to `std::defaultfloat` to get the default formatting. – Eljay Nov 03 '22 at 17:36
  • Because `1.423` is an "exact" representation for that float, `1.423000` adds nothing in terms of significant digits. `std::fixed` will keep the number of decimal places consistent, but `1.423` is "precise" to 6 decimals places already (0s are assumed, in essence). I believe most floats/doubles won't change their representation when set from a literal (so `1.423` will stay that way, it won't become the IEEE-754 value), but I'm uncertain how it is kept that way (perhaps via a static memory reference?). – Rogue Nov 03 '22 at 18:05
  • @Eljay so `defaultfloat` ignores the `setprecision()` settings? – Aashish Aggarwal Nov 03 '22 at 18:06
  • No, [`setprecision()`](https://en.cppreference.com/w/cpp/io/manip/setprecision) has different behavior for `defaultfloat`. View the code in the link. Change the value of `pi` by adding `100'000.0L` to it, and see how that affects the output. – Eljay Nov 03 '22 at 18:42

1 Answers1

-2

That's because the num (1.423) has three non-zero digits after the decimal point. Thus, it will be displayed with three decimals, trailing zeros will be skipped. This is how it is designed to work. Check these links for more information

https://cplusplus.com/reference/iomanip/setprecision/

https://en.cppreference.com/w/cpp/io/manip/fixed