IOS 四舍五入

- (NSString*)notRounding:(CGFloat)price afterPoint:(NSInteger)position {

NSDecimalNumberHandler*roundingBehavior = [NSDecimalNumberHandlerdecimalNumberHandlerWithRoundingMode:NSRoundDownscale:positionraiseOnExactness:NOraiseOnOverflow:NOraiseOnUnderflow:NOraiseOnDivideByZero:NO];

NSDecimalNumber*ouncesDecimal;

NSDecimalNumber*roundedOunces;

ouncesDecimal = [[NSDecimalNumberalloc]initWithFloat:price];

roundedOunces = [ouncesDecimaldecimalNumberByRoundingAccordingToBehavior:roundingBehavior];

return[NSStringstringWithFormat:@"%@",roundedOunces];

}


使用方法:

floats =0.126;

NSString*sb = [selfnotRounding:s afterPoint:2];

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

输出结果为:sb = 0.12


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

NSRoundDown代表的就是只舍不入。

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • - (NSString*)notRounding:(CGFloat)price afterPoint:(NSInt...
    godgnay阅读 5,090评论 8 4
  • 这个基本能够确保最后是四舍五入并且能保留两位小数。 -(float)roundFloat:(float)price...
    SunnyLeong阅读 9,491评论 0 18
  • //四舍五入-(CGFloat)roundFloat:(CGFloat)price{return (floor(p...
    guoshengboy阅读 337评论 0 0
  • 在项目中一些数字的显示难免会取整显示,四舍五入后保留一位小数,然而当最后一位是0的时候,要省略掉这个‘.0’,下面...
    TomorrowNice阅读 477评论 0 0
  • 当遇到四舍五入问题时,如果使用强转会导致精度缺失 当有需要精确到几位之后的小数的需求建议使用math.h里面的ro...
    linbj阅读 474评论 0 2