通貨スタイルでフォーマットされた UITextField (例: $ 30,034.12 => 30034.12) から double 値を取得するために、次のコードをテストしようとしました。
// Init and configure formatter
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
[formatter setMaximumFractionDigits:2];
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"us_US"];
[formatter setLocale:locale];
[formatter setGroupingSize:3];
[formatter setUsesGroupingSeparator:YES];
[formatter setGroupingSeparator:@","];
[formatter setAllowsFloats:YES];
// Get a formatted string using the local currency formatter and then get a double
// vice-versa
NSNumber *amount = [NSNumber numberWithDouble:30034.12];
NSString *amountString = [formatter stringFromNumber:amount];
// Output here OK : @"$ 30,034.12"
double amountDouble = [[formatter numberFromString:amountString] doubleValue];
// Output here NOT OK : 0
誰かが同じ問題を解決しましたか?
ありがとう !
アップデート :
@DanielBardenなど。実際には、投稿を簡素化するために、文字列をどこから取得したかを指定する部分、つまりテキスト フィールドを含めませんでした。実際、コードの最後の行は次のようになります。
NSString *amountString = [textField text];
また、このテキスト フィールドは、別の方法 (同じフォーマッタ構成を使用する通貨スタイル) からの次のコードで以前にフォーマットされていました。
// Init fromatter with style $ XXX,XXX.yy
NSNumberFormatter* formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
[formatter setMaximumFractionDigits:2];
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"us_US"];
[formatter setLocale:locale];
[formatter setGroupingSize:3];
[formatter setGroupingSeparator:@","];
[formatter setUsesGroupingSeparator:YES];
// Get the float value of the text field and format it
textField.text = [formatter
stringFromNumber:[NSNumber
numberWithDouble:[textField.text
floatValue]]];
問題は、NSLogを実行するとまったく同じ文字列が得られることですが、それらをループで文字ごとに比較すると、$の後のスペースはテキストフィールドの「実際のスペース」であり、記号の違いであることがわかります最初の文字列(最初の投稿でテストしようとした金額文字列...)。エンコーディングの問題?