[IOS]NSString转int数据丢失

从textview上面获取nsstring再转int会数据丢失,这是因为string里面可能有特殊字符,例如空格,逗号

在我的代码里,1,140转后变成1,所以使用NSNumber:

NSString * balance = [self.balanceLb.text componentsSeparatedByString:@"HKD"][1];
        
        NSLog(@"balance = %@",balance);
        NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
        f.numberStyle = NSNumberFormatterDecimalStyle;
        NSNumber *myNumber = [f numberFromString:balance];
        float balanceFloat = [myNumber floatValue];
        NSLog(@"balanceFloat = %f",balanceFloat);
        //Wrong, miss data below
        float balanceFloat = [balance floatValue];
        NSLog(@"balanceInt = %f",balanceFloat);

相关推荐