質問

選択した通貨に基づいて換算する必要がある価格があります。

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 NSNumber であり、 valueForKey も変換率で設定したplistファイルの数値です。

私が抱えている問題は、 price に小数が欠けていることです。価格からintValueを取得するたびに、切り上げまたは切り捨てられます。 plistから得た為替レートにも同じ問題があります。

NSNumberFormatter を調べましたが、NSNumberFormatterの setFormat を許可しません。アドバイスをお願いします。

役に立ちましたか?

解決

価格文字列を取得し、期間を削除します。その後、NSStringをintに変換します。つまり、最終的に4235ペニー(または42ドルと35セント)になります。 (また、取得する価格文字列が小数点以下2桁であることを確認してください!一部の人々は怠け者であり、" 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は最終価格です。

他のヒント

int は整数型です-定義上、10進数値はありません。代わりに試してください:

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

intValue は整数を返します。これは(定義により)小数点なしの数値に丸められます。

doubleValue を使用すると、double(小数部分を含む)またはNSDecimalオブジェクトを返す decimalValue を使用できます。

デシマラスの正確な数を処理し、すべての通貨が小数点以下2桁(たとえば、JPYではない)である場合、すべての数字をセント数にします 例えば43.35ユーロを4235として保存します。

その後、算術で使用し、value / 100.0とNSNumberFormatterを使用してフォーマットを処理することができます

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top