开发者

How to format float to 2 decimals in objective C

I have a 开发者_StackOverflow中文版string that I'm converting to a float that I want to check for values in an if statement.

The original float value is the iPhone's trueHeading that is returned from the didUpdateHeading method. When I convert the original float to a string using @"%.2f" it works perfectly, but what I'm trying to do is convert the original float number to the same value. IF I just convert the string to [string floatValue] I get the same original float number, and I don't want that.

To make it short and simple, how do I take an existing float value and just get the first 2 decimals?


round( x * 100.0 ) / 100.0;


float x = 123.45678;
int x1 = x * 100.0;
float x2 = (float) x1 / 100.0;

or if one-liner preferred

float x3 = (float) ((int) (x * 100.0)) / 100.0;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜