-1

Possible Duplicate:
how do you divide two integers and get a decimal answer?

This is probably really easy but I can't find the solution. I'm not a "real" programmer...

I'm storing number and scores on my app using int_64.

 .h

 int64_t score;

 @property (nonatomic, assign) int64_t score;

.m

 @synthesize score;

Here is the math:

self.score = 7/3;

The result is "2", instead of "2.33333...". I should use use something different from int_64, but what?

I wanted the result to be "2,33", with two digits after the comma. Can anyone help? Thanks!

Community
  • 1
  • 1
tomDev
  • 5,620
  • 5
  • 29
  • 39

2 Answers2

2

int stores whole numbers, also called integers. For calculations with a fractional part use double.

Also, it's better to fix the number of digits is when formatting for display. For example:

double score = 7.0/3.0;
NSString *strScore = [NSString stringWithFormat:@"%.2f", score];
Joni
  • 108,737
  • 14
  • 143
  • 193
1

You should use double to store decimal numbers instead of int. If you try to store a decimal number in an int it will get rounded.

@property (nonatomic, assign) double score;

Tim
  • 41,901
  • 18
  • 127
  • 145
  • Thx, but this is giving me the answer "2.000000". – tomDev Nov 25 '12 at 22:45
  • 1
    This only fixes half of the issue. The integer division is still done because both operands are integers. – rmaddy Nov 25 '12 at 22:49
  • You can find how to limit a double to 2 decimals here http://stackoverflow.com/questions/1113408/limit-a-double-to-two-decimal-places – Tim Nov 25 '12 at 22:51