我有一个像“1.23,45”,(德国/法国风格或其他风格)的字符串。 如何将格式删除为普通字符串或nsnumber? 我只知道从数字转换为字符串。:( 感谢。
答案 0 :(得分:2)
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
[formatter setCurrencySymbol:@""];
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[formatter setLocale:locale];
NSString *formattedOutput = [formatter stringFromNumber:[NSNumber numberWithFloat:[aPrice floatValue]]];
[locale release];
[formatter release];
NSLog(@"%@", formattedOutput];
进一步将formattedString转换为数字
NSNumber myNumber = [formattedOutput intValue]; //replace intValue by floatValue to get decimal output
答案 1 :(得分:1)
您可以使用NSString
将NSNumber
转换为NSNumberFormatter
,但您必须告诉它您的字符串使用的区域设置(在本例中为德语):
// Create a number formatter that can convert from/to German currency:
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterCurrencyStyle;
formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"de_DE"];
[formatter setLenient:YES];
// Use the number formatter to create a NSNumber:
NSNumber *number = [formatter numberFromString:@"1.23,45"];
// Return the number formatter to the current user's locale:
formatter.locale = [NSLocale currentLocale];
// Finally, create a string from the NSNumber formatted in the user's locale:
NSString *formattedString = [formatter stringFromNumber:number];
答案 2 :(得分:0)
NSNumber * myNumber = [NSNumber numberWithInt:[@"1.23,45" intValue]];
或
NSNumber * myNumber = [NSNumber numberWithFloat:[@"1.23,45" floatValue]];
注意:最好修剪字符串
中的逗号(,)符号您可以使用以下方法
+ (NSNumber *)numberWithChar:(char)value;
+ (NSNumber *)numberWithUnsignedChar:(unsigned char)value;
+ (NSNumber *)numberWithShort:(short)value;
+ (NSNumber *)numberWithUnsignedShort:(unsigned short)value;
+ (NSNumber *)numberWithInt:(int)value;
+ (NSNumber *)numberWithUnsignedInt:(unsigned int)value;
+ (NSNumber *)numberWithLong:(long)value;
+ (NSNumber *)numberWithUnsignedLong:(unsigned long)value;
+ (NSNumber *)numberWithLongLong:(long long)value;
+ (NSNumber *)numberWithUnsignedLongLong:(unsigned long long)value;
+ (NSNumber *)numberWithFloat:(float)value;
+ (NSNumber *)numberWithDouble:(double)value;
+ (NSNumber *)numberWithBool:(BOOL)value;
+ (NSNumber *)numberWithInteger:(NSInteger)value NS_AVAILABLE(10_5, 2_0);
+ (NSNumber *)numberWithUnsignedInteger:(NSUInteger)value NS_AVAILABLE(10_5, 2_0);
答案 3 :(得分:0)
听起来你需要做两件事:
1)根据逗号分隔将字符串分解为子串数组
NSString *startString = @"1.23,45";
NSArray *subStringArray= [colorStr componentsSeparatedByString:@","];
2)将每个子字符串转换为数字
NSNumberFormatter * formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSString *subString = [subStringArray objectAtIndex:0];
NSNumber *thisNumber = [formatter numberFromString:subString];
NSLog (@"thisNumber: %@", thisNumber);