将任何语言的数字转换为特定语言

时间:2014-05-22 13:26:12

标签: ios nsnumberformatter nslocale

我想在离线模式下将任何语言的数字转换为英文格式 这意味着如果我用阿拉伯语获得10.00作为“10.00”。我想将它转换回10.00。

我找到了一些链接,但我不认为在这种情况下这样做是个好主意。因为为此我必须为所有语言写作。 convert kABPersonPhoneProperty to arabic numbers

任何人都可以帮我解决这个问题

1 个答案:

答案 0 :(得分:1)

我以这种方式解决了

BOOL isCommaUsingCountry = [self ifCountryCodePresentIntheList];

NSString *strAfterReplacing = @"";
if (isCommaUsingCountry)
{
    //If some numbers come like “10.000,00”
    NSString *strAfterReplacingDot = [str stringByReplacingOccurrencesOfString:@"." withString:@""];
    strAfterReplacing = [strAfterReplacingDot  stringByReplacingOccurrencesOfString:@"," withString:@"."];

    //For removing Arabic comma
    strAfterReplacing = [strAfterReplacing  stringByReplacingOccurrencesOfString:@"٫" withString:@"."];

}
else
{
    strAfterReplacing = [str stringByReplacingOccurrencesOfString:@"," withString:@""];
}

NSArray *separray = [strAfterReplacing componentsSeparatedByString:@"."];
NSString *numbersBeforeDecimal = @"";
NSString *numbersAfterDecimal = @"";
if([separray count] == 2)
{
    numbersBeforeDecimal = [separray objectAtIndex:0];
    numbersAfterDecimal = [separray objectAtIndex:1];
}

//Converting back to US format
if([strAfterReplacing length] > 0)
{
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    NSLocale *usLocale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] autorelease];
    [formatter setLocale:usLocale];
    NSNumber *newNum1  = [formatter numberFromString:numbersBeforeDecimal];
    NSNumber *newNum2  = [formatter numberFromString:numbersAfterDecimal];
    numbersBeforeDecimal = [NSString stringWithFormat:@"%@", newNum1];
    numbersAfterDecimal = [NSString stringWithFormat:@"%@", newNum2];
}
NSString *combinedStr = [NSString stringWithFormat:@"%@.%@", numbersBeforeDecimal, numbersAfterDecimal];