0

I have a code like this...

#include<iostream>
using namespace std;
int main(){

    float num;
    cin >> num;
    cout << num;

return 0;
}

Input: 256.1024

Output: 256.102

Why does C++ automatically rounds my float to three decimals?

Mark Dickinson
  • 29,088
  • 9
  • 83
  • 120
  • 4
    Not "rounded": printed with a precision unsuited to your need. – YSC Jan 18 '22 at 22:04
  • `cout <<` rounds to 6 digits by default (the number includes digits before the dot too). – HolyBlackCat Jan 18 '22 at 22:05
  • 1
    `float` doesn't even store "decimals". Your input - whatever it may be - is converted to a float approximation. This approximation is close enough to match the first 6 or 7 decimal digits. – Drew Dormann Jan 18 '22 at 22:05
  • `cout << setprecision(4) << fixed << num;` – Eljay Jan 18 '22 at 22:06
  • 1
    The value actually stored for that input is 256.102386474609375. Check out what is happening to your bits [here](https://www.h-schmidt.net/FloatConverter/IEEE754.html). – wally Jan 18 '22 at 22:08
  • @HolyBlackCat if you have documentation specifying that it would make a good answer. If there's a statement from the standard it would make a *fantastic* answer. – Mark Ransom Jan 18 '22 at 22:09
  • Short answer, not mentioned at the duplicate - you rarely want the full precision of a floating point number because it exposes the oddities of binary representation. A rounded result is more useful most of the time. – Mark Ransom Jan 18 '22 at 22:16
  • @MarkRansom The defaults are set by [`std::basic_ios::init`](https://en.cppreference.com/w/cpp/io/basic_ios/init) (the same table is listed in the C++ standard under `[basic.ios.cons]`). – heap underrun Jan 18 '22 at 23:41

0 Answers0