@“23.0984”USD到@“23.09 USD”

时间:2012-06-05 06:44:53

标签: ios objective-c cocoa-touch

我发送的URLRequest如下所述。

NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; 
NSString *balanceString = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];

我在balanceString中得到@“23.0984 USD” 然后我想在uilabel上显示它.tex = 23.09 USD请帮帮我

3 个答案:

答案 0 :(得分:1)

可能有更简单的方法......但这应该有效..

NSString *originalString = @"23.0984 USD";
NSString *numberString   = [originalString stringByReplacingOccurrencesOfString:@" USD"
                                                         withString:@""];
float  number   = [numberString floatValue];

NSString *changedString = [NSString stringWithFormat:@"%.2f",number];

NSLog(@"ChangedString : %@ USD",changedString);

编辑:此答案已被接受。但我认为从字符串中获取数字的更好方法是搜索空格而不是替换硬编码字符串 @“USD”

NSString *originalString = @"23.0984 USD";
NSString *numberString = nil;
NSArray *parts  =  [originalString componentsSeparatedByString:@" "]; //space
if(parts && [parts lenght]){
    numberString = [parts objectAtIndex:0];
}
float number   = [numberString floatValue];

NSString *changedString = [NSString stringWithFormat:@"%.2f",number];

NSLog(@"ChangedString : %@ USD",changedString);

答案 1 :(得分:1)

NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; 
NSString *balanceString = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
float amount = [balanceString floatValue]; // This will return 23.0984 as a float
NSString *formattedAmount = [NSString stringWithFormat:@"%01.2f USD", amount];

答案 2 :(得分:1)

然后这样的事情应该有效:

    NSString * inp = @"29.2994 USD";
    // Initialize a scanner to process the input
    NSScanner * scanner = [NSScanner scannerWithString:inp];

    // Pull out a floating point value
    float v;
    [scanner scanFloat:&v];

    NSCharacterSet * ws = [NSCharacterSet whitespaceAndNewlineCharacterSet];
    // scan through the whitespace after the float
    [scanner scanCharactersFromSet:ws intoString:nil];

    NSString * currency;
    [scanner scanUpToCharactersFromSet:ws intoString:&currency];

    // write out value:
    uilabel.text= [NSString stringWithFormat:@"%.2f %@",v,currency];