开发者

How to you calculate currency values, if the "cents" portion doesn't show up?

I'm noob feeling heartache and want to give up. Let's just say I want to add 1,302.22 and ".22" portion, doesn't show up. The next currency I add 开发者_如何学Go"44.55" and fifty five cent won't show up. How do I fix this thing without giving me a headache with ".00"?


double currency = [Amount1.text doubleValue] + [Amount2.text doubleValue];
NSNumberFormatter *numberFormatter = [[[NSNumberFormatter alloc] init] autorelease];
[numberFormatter setNumberStyle: NSNumberFormatterCurrencyStyle];
NSString *numberAsString = [numberFormatter stringFromNumber:[NSNumber numberWithInt:currency]];
Currency.text = [NSString stringWithFormat:@"%@",numberAsString];


I suspect the problem lies here:

NSString *numberAsString = [numberFormatter stringFromNumber:[NSNumber numberWithInt:currency]];

[NSNumber numberWithInt:currency] creates a NSNumber object, from an integer value. The integer value you're passing in is currency. However, currency's type is a double.

An easy way to think of a double is to think of a number that has a decimal point. An easy way to think of an integer is to think of a number that doesn't have a decimal point. You can conceptually convert between the two by adding, or removing the decimal point.

Since you are passing a double into a method that expects and integer, you are getting truncation.

For example: the double 1035.55 becomes 1035 when you convert it to an int.

Try changing numberWithInt to numberWithDouble and see if you have better luck.

Also, don't give up. We've all been there :D


You can condense the code quite a bit:

double currency = [Amount1.text doubleValue] + [Amount2.text doubleValue];
Currency.text = [NSString stringWithFormat:@"%f", currency];

Don't give up, you'll get there :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜