IOS 保留小数点后几位

/******高级方法 ********/

如何只舍不入。比如 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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值