zoukankan      html  css  js  c++  java
  • IOS开发之----四舍五入问题

    http://blog.sina.com.cn/s/blog_71715bf801017nyw.html

    方法一:

    -(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代表保留小数点后几位。

    如果只入不舍怎么办,比如,float 0.162 想要得到0.17该怎么做?,在开发文档上有这样一个表,是按照保留小数点后一位处理的。相信大家一看就明白了:

    IOS开发之----四舍五入问题

     

    方法二:

     

    1、round(12345.6789) 结果为:12346

    2、round(12345.6789*100)/100 结果为:12345.68

    第二个是我要的结果,但是我不明白这么个简单的四舍五入要搞的这么复杂,应该有更好的吧,我记得在其他语言里用:round(12345.6789,2) 就可以实现四舍五入到两位小数。

     

  • 相关阅读:
    Hadoop week review
    [Q&A] VS 连接 SQLServer 时未找到或无法访问服务器
    [System] CentOS虚拟机系统克隆后的网络配置
    [Tool] csdn客户端开发(非官方版)
    [MySQL] Win7 下修改 MySQL 5.5 默认编码格式
    [Q&A] MySQL Error 1050(42S01): Table already exist
    [Matlab] libsvmmat 安装
    [SL] Silverlight + WCF Demo项目
    [Q&A] 在证书存储区中找不到清单签名证书
    谷歌浏览器当手机浏览器
  • 原文地址:https://www.cnblogs.com/xuejinhui/p/4552897.html
Copyright © 2011-2022 走看看