How exactly does rounding of double values work in C++ VS2019?

44 Views Asked by At

I have this program:

#include <stdio.h>
#include <stdlib.h>

int main()
{
  char buf[32];

  snprintf(buf, 32, "%.2f", 447.065);
  printf("447.065 --> %s\n", buf);

  snprintf(buf, 32, "%.2f", 447.165);
  printf("441.165 --> %s\n", buf);

  snprintf(buf, 32, "%.2f", 447.265);
  printf("447.265 --> %s\n", buf);

  snprintf(buf, 32, "%.2f", 447.365);
  printf("441.365 --> %s\n", buf);

  snprintf(buf, 32, "%.2f", 447.465);
  printf("447.465 --> %s\n", buf);

  snprintf(buf, 32, "%.2f", 447.565);
  printf("441.565 --> %s\n", buf);

  snprintf(buf, 32, "%.2f", 447.665);
  printf("447.665 --> %s\n", buf);

  snprintf(buf, 32, "%.2f", 447.765);
  printf("441.765 --> %s\n", buf);

  snprintf(buf, 32, "%.2f", 447.865);
  printf("441.865 --> %s\n", buf);

  snprintf(buf, 32, "%.2f", 447.965);
  printf("441.965 --> %s\n", buf);

}

This is the output:

447.065 --> 447.06 
441.165 --> 447.17 
447.265 --> 447.26 
441.365 --> 447.37 
447.465 --> 447.46 
441.565 --> 447.56 
447.665 --> 447.67 
441.765 --> 447.76 
441.865 --> 447.87 
441.965 --> 447.96 

From the output I can't understand what are the rules used for rounding the values.

I've read around and found references that the "Banker's rounding" algorithm is used in snprintf, but to me the values I got don't seem to match the values that I would have with the Banker's algorithm.

Any thoughts on this issue ?

0

There are 0 best solutions below