Integers and floating-point numbers
Quick answer
Use integers for whole quantities and floating-point values for approximate fractional measurements. Rust provides fixed-width signed and unsigned integers and floating-point types f32 and f64. Choose a type based on its range and required precision.
Range and precision
u8 represents 0 through 255; i8 represents -128 through 127. Larger widths support wider ranges. usize and isize depend on the target pointer width. Floating-point values cannot exactly represent every decimal fraction. For exact money in a fixed currency, integer minor units can be useful when the range and rounding rules are defined.
fn main() { let boxes: u8 = 12; let temperature: i8 = -8; println!("{boxes} boxes, {temperature} degrees");}Expected stdout (not executed):
12 boxes, -8 degreesThe selected types contain both values.
fn main() { let distance = 7.5_f64; let time = 2.0_f64; println!("Speed: {:.2}", distance / time);}Expected stdout (not executed):
Speed: 3.75{:.2} formats the floating-point result with two digits after the decimal point.
Common mistake
A literal like 300 cannot fit in u8. Floating-point output formatting does not turn the stored number into an exact decimal.
Try it yourself
Pick types for a 200-item count, a temperature of -15 and a measurement of 2.75. Explain the choices.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Integers and floating-point numbers — practice quiz
Choose one answer per question, then review the explanation.
Which value fits in i8?
Why can integer minor units be useful for exact prices in one currency?
Does `usize` have the same fixed width on every target?