Floating point types let us work with numbers that have decimals, like 3.14 or 0.5. They help us handle measurements, money, or any value that isn't a whole number.
0
0
Floating point types in Rust
Introduction
When you need to store numbers with fractions, like weights or temperatures.
When calculating averages or percentages that result in decimal values.
When working with scientific data that requires precision with decimals.
When you want to perform math with numbers that aren't whole, like currency conversions.
Syntax
Rust
let x: f32 = 3.14; let y: f64 = 2.71828;
f32 means 32-bit floating point number (less precise, uses less memory).
f64 means 64-bit floating point number (more precise, uses more memory).
Examples
Defines a 32-bit float and a 64-bit float with decimal values.
Rust
let pi: f32 = 3.14; let e: f64 = 2.71828;
If you don't specify, Rust assumes
f64 for decimal numbers.Rust
let temperature = 36.6; // defaults to f64
Using suffixes to explicitly set the floating point type.
Rust
let zero = 0.0_f32; let one = 1.0_f64;
Sample Program
This program calculates the total price including tax. It shows how to use f32 and f64 together by converting f32 to f64 for calculation.
Rust
fn main() {
let price: f32 = 19.99;
let tax_rate: f64 = 0.075;
let total = price as f64 * (1.0 + tax_rate);
println!("Price: ${:.2}", price);
println!("Tax rate: {:.3}", tax_rate);
println!("Total price: ${:.2}", total);
}OutputSuccess
Important Notes
Use f64 when you need more precision, like in financial or scientific calculations.
Be careful mixing f32 and f64 directly; convert one type to the other to avoid errors.
Floating point numbers can have small rounding errors, so avoid checking equality directly.
Summary
Floating point types store decimal numbers in Rust.
f32 is less precise, f64 is more precise and the default.
Use them when you need to work with numbers that have fractions.