NitroxDM
NitroxDM

Reputation: 5131

Cast int to float in F#

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

Answers (5)

feralin
feralin

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

Rob Lyndon
Rob Lyndon

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

Wesley Wiser
Wesley Wiser

Reputation: 9851

First, the function you specified has type int->int->int which means it takes 2 ints and returns an int. If you want it to use floats 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

Lee
Lee

Reputation: 144126

You can convert to a float using the float function:

let add x y = x + (float y)

Upvotes: 6

Joohwan
Joohwan

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

Related Questions