Amarsh
Amarsh

Reputation: 11804

Why is float getting rounded off in this Objective-C code?

I am doing a simple:

float x = 151.185436;
printf("x=%f",x);

and the result is

x=151.185440

Whats wrong here? I want to retain and print my original value of 151.185436.

Upvotes: 1

Views: 457

Answers (3)

Paul Tomblin
Paul Tomblin

Reputation: 182850

floats just aren't very accurate. Try double. And read this: https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html

Upvotes: 3

DenverCoder9
DenverCoder9

Reputation: 3705

A float can only hold 32 bits (4 bytes) of information about your number - it can't just store as many decimal places as you need it to. 151.18544 is as close to your value that the float could represent without running out of bits.

For the precision you want, you need to use a double instead of a float.

Upvotes: 2

pheelicks
pheelicks

Reputation: 7469

Floats are inaccurate, use doubles. Also as you're using Objective C and not straight C it might be better if you use Objective C functions for this:

myNumber = [NSNumber numberWithDouble:151.185436];
NSLog(@"myNumber = %@", myNumber);

Upvotes: 0

Related Questions