nsstring 和 int,float互相转换 小数点四舍五入

  1. NSString *tempA = @"123";NSString *tempB = @"456";
复制代码

1,字符串拼接

  1. NSString *newString = [NSString stringWithFormat:@"%@%@",tempA,tempB];
复制代码

2,字符转int

  1. int intString = [newString intValue];
复制代码

3,int转字符

  1. NSString *stringInt = [NSString stringWithFormat:@"%d",intString];
复制代码

4,字符转float

  1. float floatString = [newString floatValue];
复制代码

5,float转字符

  1. NSString *stringFloat = [NSString stringWithFormat:@"%f",intString];
复制代码

四舍五入问题


  1. -(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:保留小数点第几位,

然后调用

  1. float s =0.126;
复制代码
  1.     NSString *sb = [self notRounding:s afterPoint:2];    NSLog(@"sb = %@",sb);
复制代码

输出结果为:sb = 0.12

接下来介绍NSDecimalNumberHandler初始化时的关键参数:decimalNumberHandlerWithRoundingMode:NSRoundDown,

NSRoundDown代表的就是 只舍不入。

scale的参数position代表保留小数点后几位。

链接地址;http://my.oschina.net/u/615517/blog/140786

你可能感兴趣的:(IOS)