Shiklo Tools
PDF40
Image20
Calculators & Converters25
Text & Writing13
Developer26
Video14
Audio14
Document14
Data & Spreadsheet12
Web & SEO9
OCR & Scanning5
Archive & File12
Security & Privacy23
Health & Medical29
QR & Barcode5

Rust Numbers

Computers are very good at maths, and Rust gives you all the usual operators: + to add, - to subtract, * to multiply, / to divide and % for the remainder after dividing. Let us see them in action.

fn main() {
    let a = 17;
    let b = 5;
    println!("{} + {} = {}", a, b, a + b);
    println!("{} - {} = {}", a, b, a - b);
    println!("{} * {} = {}", a, b, a * b);
    println!("{} / {} = {}", a, b, a / b);
    println!("{} % {} = {}", a, b, a % b);
}
Output
17 + 5 = 22
17 - 5 = 12
17 * 5 = 85
17 / 5 = 3
17 % 5 = 2

Look closely at the division. 17 divided by 5 gives 3, not 3.4. When both numbers are whole numbers, Rust does whole number division and throws away the part after the point. The remainder, 2, is what is left over, just like the division you learnt in school: 5 goes into 17 three times, with 2 left.

Decimal numbers

To get the decimal answer, use decimal numbers (f64). Decimal numbers also have handy built-in abilities, called methods, such as square roots and rounding:

fn main() {
    let total = 17.0;
    let people = 5.0;
    println!("Each pays {}", total / people);
    let x: f64 = 2.0;
    println!("Square root of 2: {:.4}", x.sqrt());
    println!("2 to the power 10: {}", x.powi(10));
    println!("Rounded: {}", 7.6_f64.round());
}
Output
Each pays 3.4
Square root of 2: 1.4142
2 to the power 10: 1024
Rounded: 8

Mixing types needs as

Rust never mixes number types silently. You cannot add an i32 to an f64 directly; you first convert one of them with as. This feels strict at first, but it means you always know exactly what kind of number you have.

fn main() {
    let marks = 437;
    let subjects = 5;
    let average = marks as f64 / subjects as f64;
    println!("Average: {:.1}", average);
    let whole = average as i32;
    println!("Without decimals: {}", whole);
}
Output
Average: 87.4
Without decimals: 87

Converting a decimal to a whole number with as simply cuts off the decimal part; it does not round.

Overflow

Every number type has a largest value. An i32 stops a little above two billion. If a calculation goes past the limit, that is called overflow. When the compiler can see it coming, it refuses to build the program; when it happens while the program runs, a normal build stops with a clear message instead of quietly giving a wrong answer. If you need bigger numbers, use i64 or u64.

Practice exercises

  1. Work out how many full weeks and leftover days there are in 100 days, using / and %.
  2. Calculate the area of a circle with radius 3.5 using std::f64::consts::PI, shown with two decimals.
  3. Average three whole number marks correctly by converting them with as f64.