Search code examples
cfloating-pointformattingformat-specifiers

How do I prevent float/double format specifier from automatically changing my decimal values in C?


I have a quirky problem where if I input say 720.60 into

sscanf("%f", &amount);

where amount is of type float, the value in the variable changes to 720.59967.

How can I bypass this and prevent it from changing my value?


Solution

  • There is an alternative to using floating point if you need a fixed number of digits after the decimal point, such as 2.

    Split the input string at the ".", and treat "720.60" as two integers, 720 and 60. Multiply 720 by 100 and add 60, getting 72060. Do all your arithmetic in terms of integer numbers of hundredths. To display, print x/100 and x%100, separated by a decimal point with the second number printed as two digits with a possible leading zero.

    If you prefer to work in a floating point type, double is much more precise than float. The closest float to 720.60 is 720.5999755859375. The closest double is 720.6000000000000227373675443232059478759765625. Both would round to "720.60" if printed with only two digits after the decimal point, but rounding error can build as you do arithmetic.