Skip to content
AgileLogics
5 min read

Numbers and Math

Prerequisites: Data types

Arithmetic

printfn "%d" (7 + 3)
printfn "%d" (7 - 3)
printfn "%d" (7 * 3)
printfn "%d" (7 / 2)      // integer division
printfn "%d" (7 % 2)      // remainder
printfn "%f" (7.0 / 2.0)
printfn "%f" (2.0 ** 10.0) // power (floats only)
printfn "%d" (pown 2 10)   // integer power
10
4
21
3
1
3.500000
1024.000000
1024

Both sides of an operator must have the same type: 7 / 2.0 is a compile error. Convert with float 7 / 2.0.

Math functions

printfn "%g" (sqrt 16.0)
printfn "%d" (abs -5)
printfn "%d" (max 3 9)
printfn "%d" (min 3 9)
printfn "%g" (round 2.5)
printfn "%g" (round 3.5)
printfn "%g" (floor 2.7)
printfn "%g" (ceil 2.1)
printfn "%g" (System.Math.Round(2.345, 2))
printfn "%.4f" System.Math.PI
4
5
9
3
2
4
2
3
2.35
3.1416

Note that round uses banker's rounding (to the nearest even number when exactly halfway), the .NET default. Everything in System.Math is available too.

Integer overflow

let big = System.Int32.MaxValue
printfn "%d" big
printfn "%d" (big + 1)
printfn "%d" (int64 big + 1L)
2147483647
-2147483648
2147483648

int arithmetic wraps around silently. Use int64, or bigint for arbitrarily large integers (2I ** 100), or open Checked to make overflow throw an exception.

decimal for money

printfn "%.17f" (0.1 + 0.2)
printfn "%M" (0.1m + 0.2m)
let price = 19.99m
printfn "%M" (price * 3m)
0.30000000000000004
0.3
59.97

float can't represent 0.1 exactly; decimal can. Use decimal for currency and any value where exact decimal digits matter.

Common mistakes

  • sqrt 16 — sqrt needs a float: sqrt 16.0.
  • -5 % 3 is -2 in F# (the remainder takes the sign of the left side).
  • Comparing floats with = after calculations — use a tolerance: abs (a - b) < 1e-9.

Practice

Compute the area of a circle with radius 2.5, rounded to two decimals, and the number of whole weeks and remaining days in 45 days.

Show solution
let radius = 2.5
let area = System.Math.PI * radius ** 2.0
printfn "Area: %.2f" area
printfn "%d weeks, %d days" (45 / 7) (45 % 7)
Area: 19.63
6 weeks, 3 days