2012-12-05 50 views
2

在我的應用我嘗試檢查,如果用戶根據本地設置(如果用戶出錯,數據的PICE沒有進入CoreData數據庫)進入正確的小數點分隔符:如何使用方法「decimalSeparator」從NSNumberFormatter

- (void)save { 
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init]; 
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle]; 

NSLocale *locale = [NSLocale currentLocale]; 

我獲取用戶輸入:

NSString *firstForDistance = _forDistanceTextField.text; 

嘗試從字符串中提取小數分隔:

NSString *separator = [firstForDistance decimalSeparator]; 

比檢查分隔符是否適合用戶本地設置或他犯了錯字。在錯字或錯誤的情況下,我用小數點分隔符從他的本地設置替換:代碼

if (separator != [locale objectForKey:NSLocaleDecimalSeparator]) { 
    firstForDistance = [firstForDistance stringByReplacingOccurrencesOfString:separator withString:[locale objectForKey: NSLocaleDecimalSeparator]]; 
} 

休息:

self.user.forDistance = [numberFormatter numberFromString:firstForDistance]; 

[self.delegate usersMakeViewController:self addUser:self.user]; 
} 

這將是很好的和容易的,但提取不工作:

NSString *separator = [firstForDistance decimalSeparator]; 

方法「decimalSeparator」是來自NSNumberFormatter的實例方法,我從Xcode中得到錯誤。

我該如何解決這個問題?

回答

0

您可以檢查類似下面的字符串有decimalSeparator或不

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init]; 
    [numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle]; 
    [numberFormatter setLocale:[NSLocale currentLocale]]; 
    if ([textField.text rangeOfString:numberFormatter.decimalSeparator].location != NSNotFound) 
     NSLog(@"YES, Give number has decimalSeparator"); 
    else 
     NSLog(@"NO, dont have decimalSeparator"); 
+0

謝謝@Narayana,這也很方便,我會考慮它,但如果用戶犯了錯字(昏迷或相反的期限),取決於他的本地設置,我想替換分隔符。 – user1868438

+0

@ user1868438你能解釋更多 – Narayana

+0

我編輯了我的帖子。 – user1868438

-1

固定這樣的:

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init]; 
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle]; 

NSLocale *locale = [NSLocale currentLocale]; 
NSString *firstForDistance = _forDistanceTextField.text; 

firstForDistance = [firstForDistance stringByReplacingOccurrencesOfString:@"." withString:[locale objectForKey: NSLocaleDecimalSeparator]]; 
firstForDistance = [firstForDistance stringByReplacingOccurrencesOfString:@"," withString:[locale objectForKey: NSLocaleDecimalSeparator]]; 

self.user.forDistance = [numberFormatter numberFromString:firstForDistance]; 
[self.delegate usersMakeViewController:self addUser:self.user]; 

希望這有助於人。

+0

1,000.75 ==> 1.000.75或1,000,75?沒有(BUZZZZ!) – geowar