Tracks
/
F#
F#
/
Syllabus
/
Numbers
Nu

Numbers in F#

60 exercises

About Numbers

One of the key aspects of working with numbers in F# is the distinction between integers (numbers with no digits after the decimal separator) and floating-point numbers (numbers with zero or more digits after the decimal separator).

The two most commonly used numeric types in F# are int (a 32-bit integer) and float (a 64-bit floating-point number).

let i = 123   // Type is `int`
let d = 54.29 // Type is `float`

Both integers and floating-point numbers can use the _ character as a digit separator, which can help when defining large numbers:

let largeInt = 1_000_000
// => 1000000

let largeFloat = 9_876_543.21
// => 9876543.21

Arithmetic is done using the standard arithmetic operators (+, -, *, etc.). Numbers can be compared using the standard comparison operators (<, >=, etc.) and equality (=) and inequality (<>) operators.

5 * 6
// => 30

1.2 > 0.8
// => true

2 <> 4
// => true

To convert between numeric types, one has to use the built-in conversion operator. These operators are named after the type they will be converting to.

let floatFromInt = float 2
let intFromFloat = int 3.39

When converting between types, always be careful. If a value cannot be represented by the target type, the value will overflow.

Edit via GitHub The link opens in a new window or tab

Learn Numbers

Practicing is locked

Unlock 7 more exercises to practice Numbers