0

I have a CGFloat which I am trying to round to 1 decimal place. Using the below code, the CGFloat is rounded to 3.700000, according to NSLog:

averageRating = floorf(averageRating * 10.0f + 0.5) / 10.0f;

However, for my code to work, which depends on if statements such as:

if (averageRating == 0.1f)

I need to remove the zeros. I would like the CGFloat to always be to 1 decimal place, as I will always round it to 1 d.p. using the floorf code above.

So again: How can I remove the extra zeros from the CGFloat? All help appreciated.

Isaac A
  • 361
  • 2
  • 24

1 Answers1

0

The == operator will return 100% reliably whether two floating-point numbers are equal or not. HOWEVER two calculations that you think should give the same result will not necessarily give the same result, so unless you know exactly what you are doing, and what your compiler is doing, comparing a floating-point number against 0.1f is a very dangerous thing to do. (And obviously you don't know what you are doing, or you wouldn't be asking).

The solution is very simple:

double average_times_ten = round (averageRating * 10.0);
if (average_times_ten == 1.0) { ... }

And don't use float unless you have a very good reason to do so, which you can explain when asked about it. Use double.

gnasher729
  • 51,477
  • 5
  • 75
  • 98