← Back to Rust Course | Chapter 2: Variables & Types | Lesson 6 of 7

Floats, Booleans, and Chars

Besides whole numbers, Rust can also store numbers with decimals, simple true/false answers, and single letters or symbols.

Floating-Point Numbers

Rust has two floating-point types: f32 (single precision) and f64 (double precision, and the default). They represent numbers with fractional parts, following the IEEE 754 standard.

Example: Floating-Point Numbers

markup
fn main() {
    let price: f64 = 19.99;
    let discount: f32 = 0.15;
    println!("price: {}, discount: {}", price, discount);
}

Boolean Values

The bool type has exactly two possible values, true and false, and is one byte in size. Booleans are most commonly produced by comparison operators and consumed by if expressions.

Example: Boolean Values

markup
fn main() {
    let is_learning = true;
    let is_finished = false;
    println!("learning: {}, finished: {}", is_learning, is_finished);
}

Character Type

The char type holds a single Unicode scalar value, written in single quotes. Because Rust's char is four bytes, it can represent far more than plain ASCII letters, including emoji and characters from many languages.

Example: Character Type

markup
fn main() {
    let letter = 'R';
    let emoji = '🦀';
    println!("letter: {}, emoji: {}", letter, emoji);
}

Comparing Floats Safely

Because floating-point math can introduce tiny rounding errors, comparing two floats with == is risky. A safer approach checks that the difference between them is smaller than a small tolerance value.

Example: Comparing Floats Safely

markup
fn main() {
    let a: f64 = 0.1 + 0.2;
    let b: f64 = 0.3;
    let close_enough = (a - b).abs() < 1e-10;
    println!("a is close enough to b: {}", close_enough);
}
Common Mistakes
  1. Comparing floating-point numbers with == for exact equality, when tiny rounding errors can make them unequal.
  2. Assuming char in Rust is one byte like in C -- a Rust char is actually a 4-byte Unicode scalar value.
  3. Forgetting boolean values in Rust are strictly true/false, not 0/1 integers like in some other languages.
Chapter Summary
  • f32 and f64 represent floating-point numbers; f64 is the default and has more precision.
  • bool values are exactly true or false and are not interchangeable with integers.
  • char represents a single Unicode scalar value, written with single quotes, e.g. a or '🦀'.
  • These are all Rust's basic scalar types, alongside integers.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.