You can try to subtract (or add for a negative number) a small delta, which will not affect rounding for numbers, far enough from accuracy.
For example, if you round with %.2f , try this version on Windows:
printf("%.2f", 11.545 - 0.001);
Floating point numbers are known to be problematic if you donβt know what is happening under the covers. In this case, it is best to write (or use) a decimal type library to alleviate problems.
Program Example:
#include <stdio.h> int main (void) { printf("%.20f\n", 11.545); printf("%.2f\n", 11.545); printf("%.2f\n", 11.545 + 0.001); return 0; }
outputs this in my Cygwin environment:
11.54499999999999992895 11.54 11.55
which is suitable for your specific case (this does not happen, but we hope we will apply in another direction: you need to check it), but you should check the entire possible input range, if you want to be sure that it will work in all cases.
Update:
Eugene, based on your comment:
It works for this particular case, but not as a general solution. For example, if the number I want to format is 0.545 instead of 11.545, then "% .2f"% (0.545 - 0.001) returns "0.54", and "% .2f"% 0.545 on Linux correctly returns "0.55".
so I said that you would need to check the whole range to see if it would work, and why I said that the decimal data type would be preferable.
If you need decimal precision, this is what you will need to do. But you can consider cases in this range where Linux also goes the other way (according to your comment) - there may be a situation where Linux and Windows do not agree in the opposite direction to what you found - the decimal type probably won Solve this.
You may need to make the comparison tools a little smarter, as they can ignore the difference of 1 in the final fractional place.