2011-10-05 130 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]]; 
}