Reputation: 5131
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;
Upvotes: 29
Views: 27914
Reputation: 3408
EDIT: misread the question...
I'm pretty sure that the float()
function would do the job:
add 1.1 (float 2)
Upvotes: 37
Reputation: 12661
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.
Upvotes: 4
Reputation: 9851
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
Upvotes: 12
Reputation: 144126
You can convert to a float using the float
function:
let add x y = x + (float y)
Upvotes: 6
Reputation: 2512
Here are some examples showing the syntax for casting:
let x : int = 5 (cast x to be an integer)
let b : byte = byte x (cast b to be a byte)
Check out this link:
http://msdn.microsoft.com/en-us/library/dd233220.aspx
Upvotes: 0