2009-09-10 65 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