F# type conversion
last modified December 3, 2026
In this article we convert values between types in F#.
F# never converts between numeric types silently. Adding an
int to a float is a compile error; we have to
write the conversion ourselves. Each primitive type has a
conversion function with the same name as the type: int,
float, decimal, string and so on.
The same functions also parse strings, and .NET methods such as
Int32.TryParse parse text that may be invalid.
Conversion functions
A conversion function takes a value of one type and returns a value of another. The F# data types article lists the types; here we move values between them.
let count = 7 let price = 2.49 let total = float count * price let whole = int total let big = int64 count * 1_000_000_000L let exact = decimal count * 2.49m printfn "total: %.2f" total printfn "whole: %d" whole printfn "big: %d" big printfn "exact: %M" exact
We buy seven items for 2.49 each and convert the count and the result between integer, float and decimal types.
let total = float count * price
count is an int and price is a
float. Without the float call the compiler
reports error FS0001, because * needs two operands of the
same type.
let big = int64 count * 1_000_000_000L
Seven billion does not fit into a 32-bit int, so the count is
converted to int64 before the multiplication.
λ dotnet fsi convert.fsx total: 17.43 whole: 17 big: 7000000000 exact: 17.43
Truncation and rounding
Converting a float to an integer type drops the fractional part; the value is truncated towards zero. To round instead, we call a rounding function first and convert its result.
open System
let values = [ 2.5; 3.5; -2.7; 3.99 ]
for v in values do
printfn "%5.2f int: %2d round: %2d away: %2d floor: %2d ceil: %2d"
v (int v) (int (round v))
(int (Math.Round(v, MidpointRounding.AwayFromZero)))
(int (floor v)) (int (ceil v))
printfn "Convert.ToInt32 2.5 = %d" (Convert.ToInt32 2.5)
printfn "Decimal.Round 2.345 = %M" (Decimal.Round(2.345m, 2))
Each value is converted with truncation and with four kinds of rounding.
(int v) (int (round v))
int 3.99 is 3 and int -2.7 is -2. The
round function rounds a value that is exactly halfway to the
nearest even number, so 2.5 becomes 2 and 3.5 becomes 4. This is called
banker's rounding; it avoids a bias when many halves are rounded.
(int (Math.Round(v, MidpointRounding.AwayFromZero)))
Math.Round with MidpointRounding.AwayFromZero
rounds halves the way we learn at school. floor and
ceil round down and up. Convert.ToInt32 and
Decimal.Round also use banker's rounding.
λ dotnet fsi rounding.fsx 2.50 int: 2 round: 2 away: 3 floor: 2 ceil: 3 3.50 int: 3 round: 4 away: 4 floor: 3 ceil: 4 -2.70 int: -2 round: -3 away: -3 floor: -3 ceil: -2 3.99 int: 3 round: 4 away: 4 floor: 3 ceil: 4 Convert.ToInt32 2.5 = 2 Decimal.Round 2.345 = 2.34
Values out of range
A conversion to a smaller integer type does not check the range. The result keeps only the low bits of the value, which gives a number that has little to do with the original.
open System let total = 300 printfn "byte %d = %d" total (byte total) printfn "sbyte 200 = %d" (sbyte 200) printfn "uint32 -1 = %d" (uint32 -1) printfn "MaxValue + 1 = %d" (Int32.MaxValue + 1) printfn "int 3e9 = %d" (int 3e9) printfn "int nan = %d" (int Double.NaN)
We convert values that do not fit into the target type.
printfn "byte %d = %d" total (byte total)
A byte holds 0 to 255. 300 is 256 + 44, and only the 44 is kept. In the
same way, 200 becomes -56 as a signed byte and -1 becomes the largest
32-bit unsigned value. Integer arithmetic wraps around too:
Int32.MaxValue + 1 is the smallest int.
printfn "int 3e9 = %d" (int 3e9)
Float to integer conversions behave differently: a value that is too large
is clamped to the largest int, and nan becomes 0.
λ dotnet fsi range.fsx byte 300 = 44 sbyte 200 = -56 uint32 -1 = 4294967295 MaxValue + 1 = -2147483648 int 3e9 = 2147483647 int nan = 0
Checked conversions
The Checked module replaces the conversion functions and the
arithmetic operators with versions that check the range. When the value does
not fit, the program stops with an OverflowException instead of
continuing with a wrong number.
open Checked let total = 300 printfn "checking %d" total printfn "byte: %d" (byte total)
After open Checked, byte refuses to convert 300.
open Checked
The module affects the code that follows the open. Checked
conversions are a little slower, so they are worth using where a wrong
number would do harm, for example with money or file sizes. Only the
first lines of the error output are shown; how to catch the exception is
covered in F# exceptions.
λ dotnet fsi checked.fsx checking 300 System.OverflowException: Arithmetic operation resulted in an overflow. at <StartupCode$FSI_0001>.$FSI_0001.main@() in checked.fsx:line 6
Implicit widening
Since F# 6, the compiler converts an int to
float, int64 or nativeint when the
expected type is already known. These conversions never lose information,
so they happen without a call.
let half (x: float) = x / 2.0 let mega (x: int64) = x * 1_000_000L let n = 7 printfn "%.1f" (half n) printfn "%d" (mega n) let ratio: float = n let weights: float list = [ 1; 2; 2.5 ] printfn "%.1f %A" ratio weights let mixed = float n + 0.5 printfn "%.1f" mixed
An int is passed where a float and an
int64 are expected.
let weights: float list = [ 1; 2; 2.5 ]
The annotation says the list holds floats, so the integer elements are widened. Without it, the list would be an error.
let mixed = float n + 0.5
In an arithmetic expression no type is known in advance, so the conversion must still be written. Widening is a convenience for calls and annotated values, not a change to the rule that numeric types do not mix.
λ dotnet fsi widening.fsx 3.5 7000000 7.0 [1.0; 2.0; 2.5] 7.5
Characters and codes
A char is a UTF-16 code unit. The int function
gives its code and char turns a code back into a character.
let letter = 'A' printfn "%c = %d" letter (int letter) printfn "%d = %c" 97 (char 97) let next = char (int letter + 1) printfn "after %c comes %c" letter next let digit = '7' printfn "digit value: %d" (int digit - int '0') printfn "int64 of digit: %d" (int64 (string digit)) let lower = char (int 'Q' + 32) printfn "lower case of Q: %c" lower
We move between characters and their codes.
printfn "digit value: %d" (int digit - int '0')
int '7' is 55, the code of the character, not 7. Subtracting
the code of '0' gives the value of the digit. Another way is
to turn the character into a string and parse it.
let lower = char (int 'Q' + 32)
In ASCII the lower case letters come 32 codes after the upper case ones.
For real text, System.Char.ToLower is the safe choice, because
it handles letters outside ASCII too.
λ dotnet fsi chars.fsx A = 65 97 = a after A comes B digit value: 7 int64 of digit: 7 lower case of Q: q
Strings to numbers
The conversion functions also accept strings. They parse the text and return the number.
let age = int "42" let padded = int " 17 " let hex = int "0x1F" let height = float "1.78" let fee = decimal "12.50" let small = float "2.5e-3" printfn "%d %d %d" age padded hex printfn "%.2f %M %g" height fee small printfn "next year: %d" (age + 1)
Six strings are parsed into numbers.
let hex = int "0x1F"
Surrounding white space is ignored. int also accepts the
0x, 0o and 0b prefixes, the same as
integer literals in F# code. float and decimal
always use a dot as the decimal separator, whatever the culture of the
computer.
λ dotnet fsi parse.fsx 42 17 31 1.78 12.50 0.0025 next year: 43
Invalid input
When the text is not a number of the right kind, the conversion function
throws a FormatException, and an uncaught exception ends the
script.
let count = int "12" printfn "count: %d" count let price = int "4.5" printfn "price: %d" price
"4.5" is a valid float, but not a valid integer.
let price = int "4.5"
The second printfn never runs. The conversion functions are
fine for text that we know is correct, such as constants or data checked
earlier. For user input we use TryParse, shown in the next
section. Only the first two lines of the error output are shown.
λ dotnet fsi invalid.fsx count: 12 System.FormatException: The input string '4.5' was not in a correct format.
TryParse
Numeric types have a TryParse method that does not throw. In
F# it returns a tuple: a Boolean that tells
whether parsing succeeded, and the parsed value.
open System
let tryInt (text: string) =
match Int32.TryParse text with
| true, n -> Some n
| false, _ -> None
printfn "%A" (Int32.TryParse "125")
printfn "%A" (Int32.TryParse "12x")
let inputs = [ "8"; " 15 "; "4.5"; ""; "-3"; "seven" ]
for s in inputs do
match tryInt s with
| Some n -> printfn "%-8s -> %d" (sprintf "%A" s) n
| None -> printfn "%-8s -> not a number" (sprintf "%A" s)
let numbers = inputs |> List.choose tryInt
printfn "sum of valid numbers: %d" (List.sum numbers)
We wrap Int32.TryParse in a function that returns an
option.
match Int32.TryParse text with | true, n -> Some n | false, _ -> None
The C# signature of the method has an out parameter. F#
turns it into the second element of the returned tuple, which we take
apart with a pattern. When parsing fails, the value is 0, so it should not
be used.
let numbers = inputs |> List.choose tryInt
List.choose keeps only the values for which the function
returned Some.
λ dotnet fsi tryparse.fsx (true, 125) (false, 0) "8" -> 8 " 15 " -> 15 "4.5" -> not a number "" -> not a number "-3" -> -3 "seven" -> not a number sum of valid numbers: 20
Culture
.NET methods such as Double.TryParse use the culture of the
computer by default. In many European cultures the comma is the decimal
separator and the dot groups thousands, so the same text can mean
different numbers.
open System
open System.Globalization
let german = CultureInfo "de-DE"
let invariant = CultureInfo.InvariantCulture
let text = "3,14"
printfn "current culture: %s" CultureInfo.CurrentCulture.Name
printfn "default: %A" (Double.TryParse text)
printfn "de-DE: %A" (Double.TryParse(text, NumberStyles.Float, german))
printfn "invariant: %A" (Double.TryParse(text, NumberStyles.Float, invariant))
let amount = 1234.5
printfn "%s" (amount.ToString("N2", invariant))
printfn "%s" (amount.ToString("N2", german))
The text "3,14" is parsed with three cultures, and a number is
formatted with two.
printfn "default: %A" (Double.TryParse text)
The computer runs with en-US, where a comma separates
thousands. The text parses successfully as 314, which is the worst
outcome: a wrong number and no error.
printfn "invariant: %A" (Double.TryParse(text, NumberStyles.Float, invariant))
NumberStyles.Float allows a sign, a decimal point and an
exponent, but no thousands separator, so the invariant culture rejects the
text. Data files and protocols should be read with the invariant culture;
the user's culture is for text that people type and read.
λ dotnet fsi culture.fsx current culture: en-US default: (true, 314.0) de-DE: (true, 3.14) invariant: (false, 0.0) 1,234.50 1.234,50
Numbers to strings
The string function converts any value to text. For control
over the format we call ToString with a format string or use
the format specifiers of sprintf.
let ratio = 2.0 / 3.0 let count = 1500000 let price = 7.50m printfn "[%s] [%s] [%s]" (string ratio) (string count) (string price) printfn "[%s] [%s]" (string 3.0) (string 1e20) printfn "[%s] [%s]" (string true) (string 'x') printfn "[%s]" (ratio.ToString "F3") printfn "[%s]" (count.ToString "N0") printfn "[%s]" (count.ToString "D9") printfn "[%s]" (sprintf "%.3f" ratio) let label = "items: " + string count printfn "%s" label
Values are turned into strings with string,
ToString and sprintf.
printfn "[%s] [%s]" (string 3.0) (string 1e20)
string gives the shortest text that represents the value:
3.0 becomes 3 and large numbers use an exponent. Booleans
become True and False, with a capital letter,
unlike the true printed by %b.
string uses the invariant culture, so the output does not
depend on the computer.
printfn "[%s]" (count.ToString "N0")
F3 means three decimal places, N0 adds thousands
separators, and D9 pads an integer with zeros to nine digits.
ToString uses the current culture unless one is passed in.
λ dotnet fsi tostring.fsx [0.6666666666666666] [1500000] [7.50] [3] [1E+20] [True] [x] [0.667] [1,500,000] [001500000] [0.667] items: 1500000
Upcasts and downcasts
Conversions between a type and its base type or interface are not
numeric. The :> operator converts a value to a more general
type, and :?> converts it back. The
F# obj type article covers them in detail;
here we see how they fit with other conversions.
let scores = [ 4; 8; 15 ] let general = scores :> seq<int> printfn "%d items" (Seq.length general) let boxed = box 42 let back = boxed :?> int printfn "%d" (back + 1) let n = 42 let asFloat = float n let asObj = n :> obj printfn "%A %A" (asFloat.GetType().Name) (asObj.GetType().Name)
A list is used as a general sequence, and an integer goes into an
obj and back.
let asFloat = float n let asObj = n :> obj
The two lines look alike, but they do different things.
float creates a new value of another type. :>
keeps the same value and only changes how the compiler sees it; at run
time it is still an Int32.
λ dotnet fsi casts.fsx 3 items 43 "Double" "Int32"
Parsing measurements
The last program combines the conversions. It reads temperature measurements written as text, skips invalid lines, converts the values and prints a summary.
open System
open System.Globalization
type Reading = { Hour: int; Celsius: float }
let tryInt (s: string) =
match Int32.TryParse s with
| true, n -> Some n
| _ -> None
let tryFloat (s: string) =
match Double.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture) with
| true, x -> Some x
| _ -> None
let parseLine (line: string) =
match line.Split ';' with
| [| hour; value |] ->
match tryInt hour, tryFloat value with
| Some h, Some c -> Some { Hour = h; Celsius = c }
| _ -> None
| _ -> None
let lines = [ "6;-1.5"; "9;2.4"; "12;7.8"; "15;8,1"; "18"; "21;3.0" ]
let readings = lines |> List.choose parseLine
let average = readings |> List.averageBy (fun r -> r.Celsius)
printfn "valid readings: %d of %d" readings.Length lines.Length
for r in readings do
printfn "%02d:00 %5.1f °C %5.1f °F" r.Hour r.Celsius (r.Celsius * 9.0 / 5.0 + 32.0)
printfn "average: %.2f °C, rounded: %d °C" average (int (Math.Round average))
Each line holds an hour and a temperature separated by a semicolon.
match tryInt hour, tryFloat value with
| Some h, Some c -> Some { Hour = h; Celsius = c }
| _ -> None
Both parts must parse for the line to become a reading. The line
"15;8,1" uses a comma, which the invariant culture rejects, and
"18" has no value, so two lines are skipped.
printfn "average: %.2f °C, rounded: %d °C" average (int (Math.Round average))
The average is rounded before it is converted, so 2.925 becomes 3. A
plain int average would truncate it to 2.
λ dotnet fsi readings.fsx valid readings: 4 of 6 06:00 -1.5 °C 29.3 °F 09:00 2.4 °C 36.3 °F 12:00 7.8 °C 46.0 °F 21:00 3.0 °C 37.4 °F average: 2.92 °C, rounded: 3 °C
Source
F# language reference: Casting and conversions
.NET documentation: Parsing numeric strings
In this article we have converted values between numeric types, rounded
and truncated floats, checked for overflow, relied on implicit widening,
converted characters to codes, parsed strings with conversion functions and
TryParse, taken the culture into account, formatted numbers as
text and compared conversions with upcasts. The numeric types are described
in F# data types, format specifiers in
F# print functions, and type tests and
downcasts in F# obj type.
Author
List all F# tutorials.