4

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?

Richard-Degenne
  • 2,892
  • 2
  • 26
  • 43
Jeremy
  • 45
  • 1
  • 3
  • Years later, someone stumbled over it ^ ^ The error message comes from comparing to `0` instead of `0.0` or `0.`. – lambda.xy.x Nov 10 '18 at 01:06

2 Answers2

4

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.

Jeffrey Scofield
  • 65,646
  • 2
  • 72
  • 108
3

Since 4.08.0, round is defined in the Float module

# Float.round 2.5
- : float = 3.
# Float.round 2.4
- : float = 2.
glennsl
  • 28,186
  • 12
  • 57
  • 75
Keyi Wang
  • 39
  • 1