2009-09-10 67 views
1

我有一个价格,我需要根据所选货币进行转换。intValue缺少小数

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); 

priceNSNumbervalueForKey也从plist文件中我有一个转换率设置一个号码。

我遇到的问题是我的price缺少小数。每当我从价格中获得intValue时,它就会向上或向下四舍五入。我从plist得到的汇率也存在同样的问题。

我已经调查过NSNumberFormatter,但它不会让我为NSNumberFormatter。有什么建议吗?

+0

查找“整数”是什么意思,然后看看你是否理解这个问题。 – 2010-12-13 05:35:34

回答

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是您的最终价格。

+0

工作完美!谢谢 – runmad 2009-09-11 16:46:44

2

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

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

3

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

float fprice = [price floatValue]; 
float currencyValue = [[plistDictionary valueForKey:@"EUR"] floatValue]; 
float convertedCurrency = (fprice/currencyValue); 
+0

谢谢..这种工作。虽然现在我收到了很多数字。 例如,我的fprice是42.35,现在它写入42.3499985,而currencyValue是7.44999981而不是7.45 – runmad 2009-09-10 17:57:26

+0

这些是舍入误差,可以通过调整打印例程的格式来修正。你输入值的代码是什么? – fbrereto 2009-09-10 17:59:50

+0

现在所有我的NSLog他们......这是日志: fprice 42.349998 currencyValue 7.450000 convertedCurrency 5.684564 使用:的NSLog([的NSString stringWithFormat:@ “fprice%F”,fprice]); – runmad 2009-09-10 18:04:25

0

为了应对deciamlas的确切数目,如果您的所有货币都有2位小数(例如不JPY)使所有的数字美分 例如数量存储43.35欧元为4235.

然后你可以在算术使用,然后只处理使用格式值/ 100.0和NSNumberFormatter