将货币格式化字符串转换为普通字符

时间:2011-10-05 07:09:59

标签: objective-c currency

我有一个带有货币符号和货币格式的字符串... 我想把它转换成普通的字符串..

我的代码是这样的..

-(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]]; 
}

但问题是,当我输入字符串Rs 0.009时,它返回给我不同的值,但是使用另一个数字,它可以完美...

4 个答案:

答案 0 :(得分:1)

为什么不在将货币格式添加到它之前存储该值。通常,您只在显示之前添加货币格式,而不是存储。

答案 1 :(得分: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]];
}

答案 2 :(得分:0)

我会保持简单。

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

据我所知,NSString没有等效的NSNumberFormatter,但我可能错了。

答案 3 :(得分: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]);
相关问题