0

Rounding still won't work on the CS50 pennies problem from week1 my code is below

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

int main(void)
{
    float amount = get_float("Dollar Amount: ");
    int pennies = amount * 100;
    printf("Pennies: %i\n", pennies);
}

But this still returns if I use Davids's example of 4.20 it still rounds to 4.19 is there something I'm missing?

Thanks

Kapza
  • 1
  • 1
  • `4.20` becomes `4.19999980926513671875`, according to [IEEE-754 Floating Point Converter](https://www.h-schmidt.net/FloatConverter/IEEE754.html) – MikeCAT Jul 12 '22 at 17:28
  • `int pennies = (int)round(amount * 100);` Asssigning a floating point value to integer does not round it. It truncates the fractional part. The value `4.2` cannot be exactly represented in binary floating point. – Weather Vane Jul 12 '22 at 17:28
  • 3
    Why do you expect `#include ` to have any relevance on this? – user17732522 Jul 12 '22 at 17:28
  • 2
    BTW; **ALWAYS** prefer `double` when dealing with floating-point values. – pmg Jul 12 '22 at 17:29
  • @pmg And don't use floating-point for monetary values to being with. – user17732522 Jul 12 '22 at 17:29
  • even bitcoin should be integer: `100000000` nanoBTC or something rather than `0.1` BTC – pmg Jul 12 '22 at 17:31
  • `int pennies = amount * 100;` --> `long pennies = lround(amount * 100.0);` – chux - Reinstate Monica Jul 12 '22 at 17:50
  • @user17732522 "don't use floating-point for monetary values to being with" --> The [next version of C](https://en.wikipedia.org/wiki/C2x) may support decimal floating point. With that, using _decimal_ floating-point will be fine for money. – chux - Reinstate Monica Jul 12 '22 at 17:54

0 Answers0