Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 793
Christian Gossain Avatar asked Nov 02 '10 05:11

Christian Gossain


1 Answers

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
like image 77
cobbal Avatar answered Oct 16 '22 23:10

cobbal