I want to take the value from my slider and without rounding up, crop the decimals. So if I have a float value of 10.973. I want it in an integer as 10. I dont use negative values but if the slider value is between 0 and 1 id rather it round up. How would i make a statement doing the following?
Asked
Active
Viewed 838 times
1
-
1this is the default cast behaviour. – Bryan Chen Sep 16 '13 at 21:53
-
Even if it's the default behavior, it could be helpful to state it explicitly. People who are new to a certain programming environment don't know the assumptions. – Willem Van Onsem Sep 16 '13 at 22:02
3 Answers
1
You should use:
f = (int)floorf(x);
floorf
however will round to the lower integer so -2.79
will result in -3
.

Willem Van Onsem
- 443,496
- 30
- 428
- 555
-
-
`ceilf`. So `2.12` will result in `3`. But again `-3.98` will result in `-3` – Willem Van Onsem Sep 16 '13 at 22:34
-
-
-
I've found a post with the most common float-to-int operation: http://stackoverflow.com/a/6107681/67579 – Willem Van Onsem Sep 16 '13 at 22:40
-
-
Yes. The mathematical notation (`f` being the result of a function `f(x)`) perhaps `i = (int) ceilf(f)` was a better option :s) – Willem Van Onsem Sep 16 '13 at 23:21
0
A simple cast to integer should do:
int i = int(f)
If f is 10.973 i will be 10. If f is -10.973, i will be -10. A cast to int will simply truncate the decimal part.

Thomas Nguyen
- 464
- 1
- 5
- 16
-
-
You have the brackets around the wrong part. Should be `int i = (int)f` – danielbeard Sep 16 '13 at 22:34