1

我有一个需要根据所选货币转换的价格。

NSString *path = [[NSBundle mainBundle] bundlePath];
NSString *finalPath = [path stringByAppendingPathComponent:@"currency.plist"];
NSDictionary *plistDictionary = [[NSDictionary dictionaryWithContentsOfFile:finalPath] retain];

int price = [price intValue];
int currencyValue = [[plistDictionary valueForKey:@"EUR"] intValue];
int convertedCurrency = (price / currencyValue);

price是一个NSNumbervalueForKey也是一个来自 plist 文件的数字,我设置了转换率。

我遇到的问题是我price缺少小数点。每次我从价格中得到 intValue 时,它​​都会向上或向下取整。我从 plist 获得的汇率也存在同样的问题。

我已经调查过了NSNumberFormatter,但它不会让我setFormat使用 NSNumberFormatter。请问有什么建议吗?

4

4 回答 4

3

int是整数类型 - 根据定义,它没有十进制值。而是尝试:

float fprice = [price floatValue];
float currencyValue = [[plistDictionary valueForKey:@"EUR"] floatValue];
float convertedCurrency = (fprice / currencyValue);
于 2009-09-10T17:44:27.343 回答
2

intValue返回一个整数,该整数(根据定义)四舍五入为不带小数的数字。

您可以使用doubleValue,它返回一个 double (确实有小数部分)或decimalValue,它返回一个 NSDecimal 对象。

于 2009-09-10T17:43:04.500 回答
1

取价格字符串并删除句点。之后将 NSString 转换为 int,这意味着您最终得到 4235 美分(或 42 美元和 35 美分)。(另外,确保你得到的价格字符串有两位小数!有些人很懒,输出“3.3”代表“$3.30”。)

NSString *removePeriod = [price stringByReplacingOccurrencesOfString:@"." withString:@""];
int convertedPrice = [removePeriod intValue];
float exchangeRate;

然后根据选择的货币获取汇率并使用以下代码:

int convertedCurrency = round((double)convertedPrice / exchangeRate);
addCurrency = [NSString stringWithFormat: @"%0d.%02d", (convertedCurrency / 100), (convertedCurrency % 100)];

addCurrency 是您的最终价格。

于 2009-09-11T16:16:55.613 回答
0

要处理精确的十进制数,如果您的所有货币都有 2 个小数位(例如不是日元),则将所有数字设为美分数,例如将 43.35 欧元存储为 4235。

然后你可以在算术中使用,然后使用 value/100.0 和 NSNumberFormatter 处理格式化

于 2009-09-10T18:43:20.510 回答