NSString *str = @"4.03";
float f = [str floatValue];为什么f为4.030000002 后面哪来这么多小数? 
请问如何让转换之后还是4.03

解决方案 »

  1.   

    long tmp = f * 1000;//放大1000倍取小数后3位
    f = tmp / 1000.0;
      

  2.   

    float f = 4.3020003;
    long tmp = f * 1000;
    f = tmp / 1000.0;
    cout << f << endl;
    不要忘记/1000.0不是除1000,除1000会是4这个是最简单的方法了
      

  3.   

    如果你是输出的话,可以用sprintf("%.3f", f);
      

  4.   

    long tmp = f * 1000;这个是关键,先要转换为整形,这个去掉小数部分
      

  5.   


    有的,我的测试代码
            NSString *s = @"4.03";
            float f = [s floatValue];
            long l = f * 1000;
            f = l / 1000.0;
    通过断点,f为4.0300002
      

  6.   

    按照我的方法做肯定没问题,如果你怕溢出,最好改为64为整形quint64 tmp = f * 1000;
      

  7.   

    我的是xcode5, iOS sdk7.0
      

  8.   

    4.302
    Press any key to continue这是我的vc6.0输出结果#include <iostream.h>
    #include <stdio.h>
    void main()
    {
    float f = 4.3020003;
    long tmp = f * 1000;
    f = tmp / 1000.0;
    //printf("%.3f", f);
    cout << f << endl;

    }
      

  9.   

    强制转换试试,long tmp = (long)(f * 1000);
      

  10.   

    //使用 sprintf 和 sscanf实现吧。
    char buf[256];
    float f = 4.030002;
    snprintf(buf,sizeof(buf),"%.3f",f);//关键是利用了snprintf的格式功能
    sscanf(buf,"%f",&f);