Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

output to stream float numbers with precision

I have a problem with float numbers precision:

int main(void) {
  double b = 106.829599;
  float a = b;
  std::cerr << std::setprecision(6) << "a = " << a << "; b = " << b << std::endl;
  std::cerr << std::setprecision(7) << "a = " << a << "; b = " << b << std::endl;
}

result is:

a = 106.83; b = 106.83

a = 106.8296; b = 106.8296

So, my question is why numbers in first line are so short (I was expecting to see 106.829)

gcc 4.1.2, also I made a test at LWS

like image 743
ury Avatar asked Jan 27 '12 07:01

ury


1 Answers

Actually, 106.829599 rounded to 6 digits (3 decimals) is 106.830, which is displayed as 106.83 since 6 digits precision given to setprecision is only a maximum value.

The decimal precision determines the maximum number of digits to be written on insertion operations to express floating-point values.

What you may be looking for is combining setprecision with fixed.

like image 108
Joachim Isaksson Avatar answered Oct 09 '22 21:10

Joachim Isaksson