Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to round off Float values? [duplicate]

Tags:

objective-c

Possible Duplicate:
Rounding numbers in Objective-C

In Objective-c How to round off Float values?

like image 277
ios Avatar asked Apr 08 '11 10:04

ios


People also ask

How do you round off float numbers?

The round() function returns a floating point number that is a rounded version of the specified number, with the specified number of decimals. The default number of decimals is 0, meaning that the function will return the nearest integer.

How do you round a float to two decimal places?

Just use the formatting with %. 2f which gives you round down to 2 decimal points.

Does float round up or down?

Float number always round up.

How do you round the same number?

If the number you are rounding is followed by 5, 6, 7, 8, or 9, round the number up. For example: 38.16299 rounded to the nearest tenth is 38.2. If the number you are rounding is followed by 0, 1, 2, 3, or 4, round the number down. For example: 38.16299 rounded to the nearest hundredth is 38.16.


1 Answers

In addition to the other answers:

float theFloat = 1.23456; int rounded = roundf(theFloat); NSLog(@"%d",rounded); int roundedUp = ceil(theFloat); NSLog(@"%d",roundedUp); int roundedDown = floor(theFloat); NSLog(@"%d",roundedDown); // Note: int can be replaced by float 

For rounding to specific decimals, see the question mentioned by Alex Kazaev.

like image 123
Anne Avatar answered Oct 01 '22 14:10

Anne