-1

我正在发送如下所述的 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 上显示它请帮助我

4

3 回答 3

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);
于 2012-06-05T06:53:59.850 回答
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];
于 2012-06-05T06:54:58.450 回答
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];
于 2012-06-05T06:57:30.263 回答