您的位置:首页 > 移动开发 > IOS开发

IOS 保留小数点后几位

2014-03-25 10:40 375 查看
/******高级方法 ********/

如何只舍不入。比如 float price = 0.126,怎么样才能得到0.12?

当然,通过字符串截取的办法肯定也能达到相同的效果。但是就是这么一个简单的问题要通过一些判断和截取才能获得结果,总感觉有点笨拙。

下面先给出该问题的解决办法:

-(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 *sv = [self notRounding:s afterPoint:2];

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

输出结果为:sv = 0.12

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

NSRoundDown代表的就是 只舍不入。

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

介绍一下参数:

price:需要处理的数字,

position:保留小数点第几位,

然后调用

 

    float s =0.126;

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

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

输出结果为:sv = 0.12

 

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

NSRoundDown代表的就是 只舍不入。

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

/******  c 方法 *********/

1,四舍五入法

    float numberToRound;    int result;    numberToRound = 5.61;    result = (int)roundf(numberToRound);    NSLog(@"roundf(%.2f) = %d", numberToRound, result);    //输出 roundf(5.61) = 6
numberToRound = 5.41; result = (int)roundf(numberToRound); NSLog(@"roundf(%.2f) = %d", numberToRound, result); //输出 roundf(5.41) = 5

2、进位方法

    float numberToRound;    int result;    numberToRound = 5.61;    result = (int)ceilf(numberToRound);    NSLog(@"ceilf(%.2f) = %d", numberToRound, result);    //输出 ceilf(5.61) = 6
numberToRound = 5.41; result = (int)ceilf(numberToRound); NSLog(@"ceilf(%.2f) = %d", numberToRound, result); //输出 ceilf(5.41) = 6

3、摸位方法
    float numberToRound;    int result;    numberToRound = 5.61;    result = (int)floorf(numberToRound);    NSLog(@"floorf(%.2f) = %d", numberToRound, result);    //输出 floorf(5.61) = 5
numberToRound = 5.41; result = (int)floorf(numberToRound); NSLog(@"floorf(%.2f) = %d", numberToRound, result); //输出 floorf(5.41) = 5

转载自:http://www.cnblogs.com/yingkong1987/archive/2012/12/18/2823077.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息