2013-10-20 68 views
1

我有以下字符串:如何將貨幣字符串轉換爲數字

R $ 1.234.567,89

我需要它看起來像:1.234.567.89

我怎樣才能做到這一點?

這是我的嘗試:

NSString* cleanedString = [myString stringByReplacingOccurrencesOfString:@"." withString:@""]; 
cleanedString = [[cleanedString stringByReplacingOccurrencesOfString:@"," withString:@"."] 
            stringByTrimmingCharactersInSet: [NSCharacterSet symbolCharacterSet]]; 

它的工作原理,但我認爲必須有一個更好的辦法。建議?

回答

0

如果之前它總是$後你的電話號碼,但你有更多的字符,你可以把它像這樣:

NSString* test = @"R$1.234.567,89"; 
NSString* test2 = @"TESTERR$1.234.567,89"; 
NSString* test3 = @"HEllo123344R$1.234.567,89"; 


NSLog(@"%@",[self makeCleanedText:test]); 
NSLog(@"%@",[self makeCleanedText:test2]); 
NSLog(@"%@",[self makeCleanedText:test3]); 

方法是:

- (NSString*) makeCleanedText:(NSString*) text{ 

    int indexFrom = 0; 

    for (NSInteger charIdx=0; charIdx<[text length]; charIdx++) 
     if ('$' == [text characterAtIndex:charIdx]) 
      indexFrom = charIdx + 1; 

    text = [text stringByReplacingOccurrencesOfString:@"," withString:@"."]; 
    return [text substringFromIndex:indexFrom]; 
} 

結果是:

2013-10-20 22:35:39.726 test[40546:60b] 1.234.567.89 
2013-10-20 22:35:39.728 test[40546:60b] 1.234.567.89 
2013-10-20 22:35:39.731 test[40546:60b] 1.234.567.89 
0

如果你只是想刪除您的字符串的前兩個字符,你可以做到這一點

NSString *cleanedString = [myString substringFromIndex:2]; 
相關問題