2012-09-26 62 views

回答

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); 
+0

嗨Ramshad,我嘗試過,但它不起作用,它返回零。我認爲它不知道逗號 – iphoner

+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 
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); 
1

您可以轉換NSStringNSNumber使用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]; 
相關問題