Andrew
Andrew

Reputation: 16051

Odd int-to-string issue?

I have this code:

NSString *hString = [NSString stringWithFormat:@"%d", (h * 100)];
    HField.text = hString;

H is 0.721.

HField.text now reads:

1073741824

Any ideas why this isn't giving me 72?

Upvotes: 0

Views: 57

Answers (3)

trutheality
trutheality

Reputation: 23455

Probably because if h is 0.721 it is a float or a double, which means that the product is a float or a double, which means that you should cast it to int first or use %f.

Upvotes: 3

Sascha Galley
Sascha Galley

Reputation: 16101

with %d you are refering to an integer

try %f instead:

NSString *hString = [NSString stringWithFormat:@"%f", (h * 100)];

Upvotes: 2

Alexsander Akers
Alexsander Akers

Reputation: 16024

Ah. The problem is that h seems to be a double or float. Try this:

HField.text = [NSString stringWithFormat: @"%f", (h * 100.0)];

This should work. You have to use %f for floating-point numbers and %d for integers.

Edit

HField.text = [NSString stringWithFormat: @"%d", (NSInteger) round(h * 100.0)];

Round will round the float to an integer. You can alternately use ceil() or floor() to round up or down, respectively. The (NSInteger) cast is there to make sure it is converted to an integer.

Upvotes: 5

Related Questions