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;
To convert the integer to float, use the float() function in Python. Similarly, if you want to convert a float to an integer, you can use the int() function.
Type casting refers to changing an variable of one data type into another. The compiler will automatically change one type of data into another if it makes sense. For instance, if you assign an integer value to a floating-point variable, the compiler will convert the int to a float.
You can't reassign i as a float after that. An int is always an int and will remain an int as long as it was declared as an int and will never be able to change into anything but an int.
EDIT: misread the question...
I'm pretty sure that the float()
function would do the job:
add 1.1 (float 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
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