2011-10-05 124 views
4

我曾用一個字符串貨幣符號和貨幣格式... 我想將其轉換成正常的字符串..轉換貨幣格式化字符串正常的字符串

我的代碼是這樣的..

-(NSString *)removeCurrency:(NSString *)str{ 


    NSNumberFormatter *_currencyFormatter = [[NSNumberFormatter alloc] init]; 
    [_currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle]; 
    [_currencyFormatter setNegativeFormat:@"-¤#,##0.00"]; 

    NSLog(@"\n With Currency : %@",str); 
    NSLog(@"\n Without Currency : %@",[_currencyFormatter numberFromString:str]); 

    return [NSString stringWithFormat:@"%@",[_currencyFormatter numberFromString:str]]; 
} 

但問題是有,當我輸入的字符串盧比0.009還給了我不同的值,但與其他數它的作品完美...

+0

檢查[這個問題的答案] [1],我希望它有幫助。 [1]:http://stackoverflow.com/questions/1156347/cocoa-nsnumberformattercurrencystyle-without-return-zero – Mousa

+1

你能否提供更多細節,比如怎樣用這種方法被調用,什麼實際值str被傳入了嗎? – ericg

回答

0

我只想保持簡單。

NSString *stringWithoutCurrency = [str stringByReplacingOccurrencesOfString:@"$" withString:@""]; 

從我可以告訴,有一個的NSString的不等價NSNumberFormatter,但我可能是錯的。

1

爲什麼不保存您添加的貨幣格式到它之前的值。通常,只添加了貨幣,你之前顯示格式,而不是存儲。

0

你說用「RS 0.009」你會得到不同的值。是價值0.008999999999999999,通過任何機會呢?如果是這樣,你實際上得到了正確的結果。把它弄到浮點不準確。

下面是一些代碼,顯示了這一點:

NSString* str = @"Rs 0.009"; 

NSNumberFormatter *_currencyFormatter = [[NSNumberFormatter alloc] init]; 
[_currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle]; 
[_currencyFormatter setCurrencyCode:@"INR"]; 
[_currencyFormatter setLenient:YES]; 
[_currencyFormatter setCurrencySymbol:@"Rs"]; 

NSLog(@"\n With Currency : %@",str); 
NSLog(@"\n Without Currency : %@",[_currencyFormatter numberFromString:str]); 
NSLog(@"\n Without Currency : %f",[[_currencyFormatter numberFromString:str] floatValue]); 
NSLog(@"\n Without Currency : %.03f",[[_currencyFormatter numberFromString:str] floatValue]); 
1

,如果你設置的貨幣按區域設置比你可以使用當前的區域刪除符號,並得到串

-(NSString *)removeCurrency:(NSString *)str{ 

    NSLocale *currentLocale = [NSLocale currentLocale]; 
    NSString *currency = [currentLocale objectForKey:NSLocaleCurrencySymbol]; 
    NSNumberFormatter *_currencyFormatter = [[NSNumberFormatter alloc] init]; 
    NSString *currencyCode=[currentLocale objectForKey:NSLocaleCurrencyCode]; 
    [_currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle]; 

    [_currencyFormatter setCurrencyCode:currencyCode]; 
    [_currencyFormatter setLenient:YES]; 
    [_currencyFormatter setCurrencySymbol:currency]; 

    NSLog(@"\n Currency : %@",currency); 
    NSLog(@"\n Without Currency : %@",[_currencyFormatter numberFromString:str]); 
    NSLog(@"\n Without Currency : %f",[[_currencyFormatter numberFromString:str] floatValue]); 
    // NSLog(@"\n Without Currency : %.03f",[[_currencyFormatter numberFromString:currency]]); 

    NSLog(@"\n With Currency : %@",str); 
    NSLog(@"\n Without Currency : %@",[_currencyFormatter numberFromString:str]); 

    return [NSString stringWithFormat:@"%@",[_currencyFormatter numberFromString:str]]; 
}