Christian Gossain
Christian Gossain

Reputation: 5972

How can I round down a float?

I need to somehow round down float values with a precision of two decimal points, for futhur computation.

For example if I have 0.1098 I need it to become 0.10 and if i have 0.1176 I need that to become 0.11.

Pretty much I guess I need to truncate my floats to 2 decimal points

Upvotes: 5

Views: 2331

Answers (1)

cobbal
cobbal

Reputation: 70733

usually you do rounding when converting it to a string, since binary floats can't always exactly represent 2 decimal digits. To get an NSString with 2 digits, use

[NSString stringWithFormat:@"%.02f", num];

If you really want to truncate to a float for further computation, use something like

((int)(num * 100)) / 100.0

and if you want to round instead of truncate

((int)(num * 100 + 0.5)) / 100.0

Upvotes: 14

Related Questions