floor(x) vs int(x)

Discussion and feedback on Construct 2

Post » Wed Nov 28, 2012 4:15 am

All,

Just out of curiosity, what is the difference (if any) between using floor(x) and int(x)? I noticed they were listed in different sections in the manual.

Thanks
B
11
S
2
G
2
Posts: 26
Reputation: 2,974

Post » Wed Nov 28, 2012 6:01 am

Wouldn't floor() round down while int() would do rounding both ways? Int() would also be used to convert other types into integers.
B
24
S
8
G
7
Posts: 756
Reputation: 7,192

Post » Wed Nov 28, 2012 8:17 am

int() probably doesn't guarantee that the rounding will necessarily be rounded up or down. I would usually expect an int() function to simply truncate the value -- effectively rounding down -- but it also wouldn't be out of the question for it to round to the nearest integer value instead, and given the behaviour isn't specifically listed in the manual it's also possible that this implementation detail might be changed at some point and should not be relied on to always stay the same.

However, let's assume that there's no technical difference and that both functions will have the same effect: each function still expresses a different intent, and you should use whichever more accurately expresses what you intend on doing. You int() when you want to convert a value to an integer, round() if you want to round to the nearest integer value, and floor() or ceil() if you'd like to round up or down.

By choosing a function that clearly expresses your intent you increase readability of your code and reduce the need for explanatory comments.

B
24
S
5
G
2
Posts: 104
Reputation: 3,136

Post » Wed Nov 28, 2012 2:25 pm

I think they're identical. The reason they both exist is mainly for consistency. There are three convert-to-type operators: int(), float() and string(). There are also three rounding functions: floor(), ceil() and round(). If you've come from other programming languages or tools you might expect both sets of three to be present. It just so happens int() is identical to floor() in implementation, but I kept them so people don't wonder why the int() conversion operator is missing or why there's no floor() when there's ceil().
Scirra Founder
B
357
S
214
G
72
Posts: 22,945
Reputation: 178,206


Return to Construct 2 General

Who is online

Users browsing this forum: gamecorpstudio, Zonacas and 14 guests