How to format a float to 2 decimal places in a C object

I have a string that I convert to a float that I want to check for values ​​in an if statement.

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

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

+4
source share
2 answers
round( x * 100.0 ) / 100.0; 
+8
source
 float x = 123.45678; int x1 = x * 100.0; float x2 = (float) x1 / 100.0; 

or if one liner prefers

 float x3 = (float) ((int) (x * 100.0)) / 100.0; 
+2
source

Source: https://habr.com/ru/post/1308312/


All Articles