如何从NSString中提取前3个字符?
例如,如果我有一个字符串“1234820”如何从字符串中提取数字123并将结果存储在格式为“1.23百万”的新字符串中?
我使用
计算字符串中的字符数 -(NSString *)returnFormattedString:(NSString *)stringToFormat{
NSString *formatedString;
NSUInteger characterCount = [stringToFormat length];
if (characterCount > 6) {
//???? How do I extract and add a decimal
stringWithThreeCharactersAndDecimal = ????;
NSString *string = [NSString stringWithString:stringWithThreeCharactersAndDecimal];
formatedString = [string stringByAppendingString:@"Million"];
}
return formatedString;
}
答案 0 :(得分:1)
喜欢
assume that is your String
yourString = @"1234820";
// use substringToIndex for fetch First Three Character
yourString=[yourString substringToIndex:3];
// finally convert string to as like 1.23
NSString *finalStr = [NSString stringWithFormat:@"%.2f Million", [yourString floatValue]];
选择-2
根据Droppys简短而且答案很好
NSString *finalStr = [NSString stringWithFormat:@"%.2f Million", [yourString floatValue] / 100.0f];