私は解決策を見つけました。この質問の目的に従って、将来この問題を抱えている人に完全な回答を提供します. まず、NumberFormatting という新しいヘルパー クラスを作成し、2 つのメソッドを作成しました。
//
// NumberFormatting.h
// Created by Noah Hendrix on 12/26/09.
//
#import <Foundation/Foundation.h>
@interface NumberFormatting : NSObject {
}
-(NSString *)stringToCurrency:(NSString *)aString;
-(NSString *)decimalToIntString:(NSDecimalNumber *)aDecimal;
@end
実装ファイルは次のとおりです。
//
// NumberFormatting.m
// Created by Noah Hendrix on 12/26/09.
//
#import "NumberFormatting.h"
@implementation NumberFormatting
-(NSString *)stringToCurrency:(NSString *)aString {
NSNumberFormatter *currencyFormatter = [[NSNumberFormatter alloc] init];
[currencyFormatter setGeneratesDecimalNumbers:YES];
[currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
if ([aString length] == 0)
aString = @"0";
//convert the integer value of the price to a decimal number i.e. 123 = 1.23
//[currencyFormatter maximumFractionDigits] gives number of decimal places we need to have
//multiply by -1 so the decimal moves inward
//we are only dealing with positive values so the number is not negative
NSDecimalNumber *value = [NSDecimalNumber decimalNumberWithMantissa:[aString integerValue]
exponent:(-1 * [currencyFormatter maximumFractionDigits])
isNegative:NO];
return [currencyFormatter stringFromNumber:value];
}
-(NSString *)decimalToIntString:(NSDecimalNumber *)aDecimal {
NSNumberFormatter *currencyFormatter = [[NSNumberFormatter alloc] init];
[currencyFormatter setGeneratesDecimalNumbers:YES];
[currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
if (aDecimal == nil)
aDecimal = [NSDecimalNumber zero];
NSDecimalNumber *price = [NSDecimalNumber decimalNumberWithMantissa:[aDecimal integerValue]
exponent:([currencyFormatter maximumFractionDigits])
isNegative:NO];
return [price stringValue];
}
@end
最初のメソッド stringToCurrency は、整数 (この場合はテキストフィールドから渡されます) を受け取り、ユーザーのロケール設定に応じて小数点を移動して 10 進数値に変換します。次に、NSNumberFormatter を使用して通貨としてフォーマットされた文字列表現を返します。
2 番目の方法は、1.23 のような値を取り、同様の方法を使用してそれを 123 に戻す逆の処理を行います。
これが私がそれをどのように使用したかの例です
...
self.accountBalanceCell.textField.text = [[NumberFormatting alloc] decimalToIntString:account.accountBalance];
...
[self.accountBalanceCell.textField addTarget:self
action:@selector(updateBalance:)
forControlEvents:UIControlEventEditingChanged];
ここでは、テキスト フィールドの値をデータ ストアからの 10 進数値に設定し、オブザーバーを設定してテキスト フィールドへの変更を監視し、メソッド updateBalance を実行します。
- (void)updateBalance:(id)sender {
UILabel *balanceLabel = (UILabel *)[accountBalanceCell.contentView viewWithTag:1000];
NSString *value = ((UITextField *)sender).text;
balanceLabel.text = [[NumberFormatting alloc] stringToCurrency:value];
}
これは単純に textfield 値を取得し、上記の stringToCurrency メソッドで実行します。
私にはこれはハックのように思えるので、使用することに興味がある場合は、少し時間をかけて全体を調べてクリーンアップしてください。また、値が大きいと壊れることに気付きます。