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?
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.
Since 4.08.0, round
is defined in the Float
module
# Float.round 2.5
- : float = 3.
# Float.round 2.4
- : float = 2.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With