简体   繁体   English

在目标C中浮点数到字符串的转换

[英]float to string conversion in objective C

I am converting float to string using this method 我正在使用此方法将float转换为字符串

    -(NSString*)FloatToStr:(float)floatVal
      {
            NSString *string;
            string=[NSString stringWithFormat:@"%0.02f",floatVal];
            return string;
      }

    float x=15.625;
    NSLog(@"c==>%@",[self FloatToStr:x]);

    //Output:15.62

it gives the 15.62, but i want 15.63. 它给出了15.62,但我想要15.63。

In your code you are truncating the number to two decimals positions. 在代码中,您将数字截断为两位小数。 If you want to round to two decimals, make this before to convert to string. 如果要舍入到小数点后两位,请先将其转换为字符串。

-(NSString*)FloatToStr:(float)floatVal
{
NSString *string;
string=[NSString stringWithFormat:@"%0.02f",roundf(floatVal*100)/100];
return string;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM