0

I have a problem with my float variable, i have to do some operation and then i have a final number what I saw is that some time the number is not correct, but just for a point for example when i have this number and i try to print it i don't give me back the same number:

float myNumber = 27589353.0f; NSLog(@"My Number is %.2f", myNumber); 

the result is: My Number is 27589352.00

I've tried to put the variable double but i have the same issue.

8
  • 2
    floating-point-gui.de -- foating-point types aren't exact. Commented Oct 30, 2013 at 0:29
  • That's too much precision for float. Use double. Commented Oct 30, 2013 at 0:30
  • @rmaddy "I've tried to put the variable double but i have the same issue." Commented Oct 30, 2013 at 0:30
  • @H2CO3 Oops - I guess I didn't make it to the last line. My bad. :) Commented Oct 30, 2013 at 0:32
  • 2
    @rmaddy I understand, it's quite tiring to read the same (or similar) questions agin and again. The brain says "whoops I've seen this before" and just substitutes things before actually reading. That's how it works out :) Commented Oct 30, 2013 at 0:34

2 Answers 2

1

The problem is that floats do not have enough precision, as maddy said in the comments above.

And this code:

double myNumber = 27589353.0f; NSLog(@"My Number is %.2f", myNumber); 

Won't work either because the "f" qualifier on the constant forces the number to be a float, causes the loss of precision, then promotes the value to a double, once the damage is done.

This code however, will work correctly:

double myNumber = 27589353.0; NSLog(@"My Number is %.2f", myNumber); 

(Note that I'm assigning a floating point value with a decimal, but no final "f"

Sign up to request clarification or add additional context in comments.

Comments

-1

try like that it's work, you have to remove the 'f' as well

double myNumber = 27589353.0; NSLog(@"My Number is %.2f", myNumber); 

6 Comments

That's not right either. You are making myNumber a long integer, which can't store floating point values. That tap-dances around the issue. See my post below for the solution.
(Or see my comment above. You couldn't even get it right after copying that.)
when i post my answer the comment is not there -.- I have answer a similar answer a couple of days ago, @DuncanC what i tell Him is just that the problem is the 'f' so now i'm update my answer you can remove your -1 -.-
You answered 38 minutes ago, my comment was 42 minutes ago. And just how is %.2ld going to format a double?
I don't want still nothing you can see that i'm answer a same answer some days ago -.-
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.