Cast int to float in F#
Solution 1
EDIT: misread the question...
I'm pretty sure that the float()
function would do the job:
add 1.1 (float 2)
Solution 2
First, the function you specified has type int->int->int
which means it takes 2 int
s and returns an int
. If you want it to use float
s you need to specify the type of one of the arguments:
let add (x : float) y = x + y
//add : float->float->float
As others have mentioned, you can cast to a float
using the float()
function:
float 2 //2 : float
If you are using numeric literals like in your example, you can just use 2.0
instead of 2
which has the float
type.
add 1.1 2.0
Solution 3
You can convert to a float using the float
function:
let add x y = x + (float y)
Solution 4
Because float
is a function, there is a certain elegance to
add 1.1 (j |> float)
On the face of it, that's not much better than add 1.1 (float 2)
, but if you want to convert the result of a long calculation to a float, the forward pipe can be very useful.
NitroxDM
Updated on July 09, 2022Comments
-
NitroxDM over 1 year
Learning F#, the syntax is still quite foreign to me. How do I cast this integer to float?
let add x y = x + y let j = 2 add 1.1 j
In C# Float + int= Float
float j = 1.1f + 5;