Reputation: 45
I want if it is bigger or equal to 0 to round it to the bigger number and if it is smaller than 0 to round it to the number before. Eg: If the number is 2.5 show 3 and if the number is -2.5 show -3. How should i write this? I wrote :
let round x = if (x >= 0) then int_of_float x
else int_of_float ( x -. 1.0);;
or
let round x = if ( x>=0) then truncate (x +. 0.5)
else truncate ( x -. 0.5);;
and to both it gives me the same error :
Error: This expression has type int but an expression was expected of type
float
How should I write it?
Upvotes: 4
Views: 5953
Reputation: 39
Since 4.08.0, round
is defined in the Float
module
# Float.round 2.5
- : float = 3.
# Float.round 2.4
- : float = 2.
Upvotes: 3
Reputation: 66803
The compiler is complaining because 0
is a constant of type int
. It will work better if you use 0.0
.
Personally I use this definition:
let frnd f = floor (f +. 0.5)
However, it doesn't work exactly like you want:
# frnd 2.5;;
- : float = 3.
# frnd (-2.5);;
- : float = -2.
# frnd (-2.500000001);;
- : float = -3.
I.e., it rounds up (toward positive infinity) values halfway between integers.
Upvotes: 5