Chuyển đến nội dung

Bài 5 · Language Basics

F# Basic Types: Integers, Floats, Bool, Char and More

A tour of F# primitive types: int, int64, byte, float, decimal, bool, char, numeric literals and suffixes, overflow behaviour, and how to convert between types explicitly.

F# is strongly typed, and its basic types map directly onto .NET types. You will use int, float, bool, char and string constantly, plus a handful of sized numbers when precision or range matters. This lesson shows each type, its literal syntax, and the main rule that surprises newcomers: F# never converts numeric types for you.

The common types

F# type .NET type Example literal Notes
int Int32 42, 0xFF, 0b1010 32-bit signed
int64 Int64 42L 64-bit signed
byte Byte 255uy 0 to 255
uint32 UInt32 42u unsigned
float Double 3.14, 1e6 64-bit
float32 Single 3.14f 32-bit
decimal Decimal 19.99m exact decimal, for money
bigint BigInteger 123456789012345678901I unlimited size
bool Boolean true, false
char Char 'a' single UTF-16 unit
string String "hello" immutable text
unit Unit () "no value"

The names double and single are also accepted as aliases for float and float32.

FSHARP
let population = 8_000_000_000L      // underscores make big numbers readable
let mask = 0b1010_1010
let hex = 0xFF
let ratio = 2.5e-3
let price = 19.99m

Integers and overflow

Integer arithmetic stays within the type. By default, F# arithmetic is unchecked: it wraps around silently.

FSHARP
let big = System.Int32.MaxValue
let wrapped = big + 1
printfn "%d" wrapped        // -2147483648

To get an exception instead, open the Checked operators:

FSHARP
open Microsoft.FSharp.Core.Operators.Checked

let boom = System.Int32.MaxValue + 1   // raises OverflowException

Integer division truncates toward zero, and % is the remainder:

FSHARP
printfn "%d" (7 / 2)        // 3
printfn "%d" (-7 / 2)       // -3
printfn "%d" (7 % 2)        // 1

Dividing an integer by zero throws DivideByZeroException. Dividing floats by zero gives infinity or nan instead.

Floating-point and decimal

float follows IEEE 754, so it cannot store most decimal fractions exactly:

FSHARP
printfn "%b" (0.1 + 0.2 = 0.3)       // false
printfn "%.17f" (0.1 + 0.2)          // 0.30000000000000004

Never use float for money. decimal stores base-10 digits and is the right choice for currency. Use float for science and graphics.

Floats have the special values nan, infinity and -infinity. A trap: nan = nan is false. Use System.Double.IsNaN x to test.

No implicit conversions

Mixing types in one expression is an error:

FSHARP
let a = 3
let b = 2.5
let c = a + b      // error: the type 'float' does not match 'int'

You convert explicitly with a function named after the target type:

FSHARP
let c = float a + b       // 5.5
let d = int 3.99          // 3 (truncates)
let e = int64 a           // 3L
let f = decimal 2.5       // 2.5M

This may feel strict at first. It prevents an entire class of silent-precision and overflow bugs, and the error messages tell you exactly where to add the conversion. The rounding helpers live in the Operators and Math:

FSHARP
printfn "%f" (round 2.5)        // 2.000000 (banker's rounding: to even)
printfn "%f" (floor 2.7)        // 2.000000
printfn "%f" (ceil 2.1)         // 3.000000
printfn "%f" (truncate -2.7)    // -2.000000

round rounds halves to the nearest even number, so round 3.5 is 4.0 and round 2.5 is 2.0.

bool

bool has two values and the operators && (and), || (or) and not. Both && and || short-circuit: the right side runs only if needed.

FSHARP
let isAdult age = age >= 18
let canVote age citizen = isAdult age && citizen
let weekend day = day = "Sat" || day = "Sun"

Equality is = and inequality is <> (not !=).

char

A char is written in single quotes. Characters convert to and from their numeric code:

FSHARP
let letter = 'F'
let code = int letter          // 70
let next = char (code + 1)     // 'G'
printfn "%c %d %c" letter code next

Useful helpers are System.Char.IsDigit, IsLetter, IsUpper, and ToUpper.

Type abbreviations and units of measure (preview)

You can alias a type for readability, and F# even lets you attach units of measure such as m or kg to numbers so the compiler rejects adding meters to seconds. Both are covered later; for now just know that numbers in F# can carry more meaning than in most languages.

FSHARP
type Money = decimal

Try the ideas in C#

C# has the same underlying types, and the same wrap-around and truncation rules. These runnable stand-ins show integer division and the float-equality trap. The C# decimal result is the exact one F# gives for decimal.

C# C# stand-in: integer division and overflow

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# C# stand-in: double versus decimal

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Check your understanding

Quick check · 5 questions

of 5 answered You scored / 5 · perfect!

  1. 1. What does 3 + 2.5 do in F#?

    F# has no implicit numeric conversions. Write float 3 + 2.5.
  2. 2. What is -7 / 2 for ints?

    Integer division truncates toward zero, giving -3.
  3. 3. Which type should you use for currency amounts?

    decimal stores exact base-10 values, avoiding floating-point rounding surprises.
  4. 4. How do you write "not equal" in F#?

    F# uses <> for inequality; != is not an F# operator.
  5. 5. What does the literal 42L denote?

    The L suffix makes an int64 literal.

Summary

  • F# primitives are .NET types: int, int64, byte, float, decimal, bigint, bool, char, string, unit.
  • Literal suffixes (L, uy, f, m, I) pick the type; underscores split long numbers.
  • Integer arithmetic wraps unless you open Checked; integer division truncates.
  • There are no implicit numeric conversions: use float, int, decimal and friends.
  • Use decimal for money, float for science, and <> for inequality.

Next: Strings and formatting

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.