天天看點

Objective-C中NSString與int和float的互相轉換

NSString *tempA = @"123";

NSString *tempB = @"456";

1,字元串拼接

 NSString *newString = [NSString stringWithFormat:@"%@%@",tempA,tempB];

2,字元轉int

int intString = [newString intValue];

3,int轉字元

NSString *stringInt = [NSString stringWithFormat:@"%d",intString];

4,字元轉float

 float floatString = [newString floatValue];

5,float轉字元

NSString *stringFloat = [NSString stringWithFormat:@"%f",intString];

四舍五入問題

-(NSString *)notRounding:(float)price afterPoint:(int)position{

    NSDecimalNumberHandler* roundingBehavior = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundDown scale:position raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:NO];

    NSDecimalNumber *ouncesDecimal;

    NSDecimalNumber *roundedOunces;

    ouncesDecimal = [[NSDecimalNumber alloc] initWithFloat:price];

    roundedOunces = [ouncesDecimal decimalNumberByRoundingAccordingToBehavior:roundingBehavior];

    [ouncesDecimal release];

    return [NSString stringWithFormat:@"%@",roundedOunces];

}

介紹一下參數:

price:需要處理的數字,

position:保留小數點第幾位,

然後調用

    float s =0.126;

    NSString *sb = [self notRounding:s afterPoint:2];

    NSLog(@"sb = %@",sb);

輸出結果為:sb = 0.12

接下來介紹NSDecimalNumberHandler初始化時的關鍵參數:decimalNumberHandlerWithRoundingMode:NSRoundDown,

NSRoundDown代表的就是 隻舍不入。

scale的參數position代表保留小數點後幾位。

繼續閱讀