2

I'm solving cs50 pset1, I need first 2 decimal places. I'm trying to get it by converting the float I get from the user to int, then substracting it from float and then multiplying by 100 to get 2 decimal places

for ex input 9.41 after subustracting i get .410000 but when multiplying by 100 i get 40.9999 as output whereAS I need exact 41 so i can convert to int

    #include<stdio.h>
    #include<cs50.h>
    #include<math.h>

    int main(void)
    {
        int i = 0;
        float number = get_float("Enter change: ");
        printf("%f \n",number);
        int integer = (int)number;
        printf("%i \n",integer);
        float change = number - integer;
        printf("%f \n",change);
        change = change * 100;
        printf("%f \n",change);
        int n = (int)change;

        printf("%i \n",n);
    }

expected:


Enter change: 9.41
9.410000 
9 
0.410000 
41.000000 
41 

actual:

Enter change: 9.41
9.410000 
9 
0.410000 
40.999985 
40
Adam
  • 2,726
  • 1
  • 9
  • 22
Rohit_
  • 73
  • 1
  • 8
  • 6
    This is why you should not use floats for currency. – klutt Jun 13 '19 at 10:24
  • `%f` -> `%.2f` and also read the specs of `printf`, especially the variations of the `%f` format specifier, and this https://stackoverflow.com/questions/588004/is-floating-point-math-broken. – Jabberwocky Jun 13 '19 at 10:26
  • So if i cant use floating points due to their imprecision, then what are other options? – Rohit_ Jun 13 '19 at 10:42
  • Quick (possibly innacurate) fix: before converting to int add `0.5` --- `int n = (int)(change + 0.5);` – pmg Jun 13 '19 at 10:52
  • 3
    @RohitJain use integer for currency. Store amount of cents. This avoids all problems with inaccuracies. – Andreas H. Jun 13 '19 at 10:53
  • 4
    @AndreasH.: Using integer does not “avoid all problems with inaccuracies.” Integer arithmetic cannot represent the unit price of products sold three for a dollar. When computing sales tax, inaccuracies will occur and must be worked around by the programmer. Inaccuracies due to overflow may occur and must be guarded against. – Eric Postpischil Jun 13 '19 at 11:17
  • @EricPostpischil. Working with integers just forces the programmer to employ/think about the correct rounding mode, as e.g. either mandated by rules or quasi standards (bankers rounding). So true, the programmer has to work around the issues, but I think there is no way around it (no matter how you implement financial calculations). Even if it may sounded so, I did not mean that the problems with inaccuracies just vanish automatically. – Andreas H. Jun 13 '19 at 12:16
  • Thank you, I just rounded it off to the nearest integer before using – Rohit_ Jun 13 '19 at 14:15

0 Answers0