Skip to main content
f32 is a primitive data type in Rust representing a 32-bit, single-precision floating-point number. It strictly adheres to the IEEE 754-2008 standard for floating-point arithmetic.

Memory Layout

At the hardware level, an f32 occupies exactly 4 bytes (32 bits) of memory, divided into three components:
  • Sign: 1 bit (determines positive or negative)
  • Exponent: 8 bits (determines the magnitude)
  • Mantissa (Fraction): 23 bits (determines the precision)

Syntax and Initialization

Rust provides multiple ways to instantiate an f32. If a floating-point literal lacks a type suffix or explicit annotation, Rust defaults to f64. Therefore, explicit typing is required to bind a literal to an f32.

Precision and Constants

Because of the 23-bit mantissa, an f32 provides approximately 6 to 9 significant decimal digits of precision. Operations requiring higher precision will suffer from floating-point rounding errors. The std::f32 module provides associated constants for boundary values:

Special IEEE 754 Values

f32 supports special non-numeric states defined by the IEEE 754 standard:

Trait Implementations and Type System Constraints

The f32 type implements standard mathematical operators (Add, Sub, Mul, Div, Rem) and bitwise copy semantics (Copy, Clone). Crucially, f32 implements PartialEq and PartialOrd, but does not implement Eq or Ord. This is because f32::NAN == f32::NAN evaluates to false, violating the reflexivity requirement of total equality.
Because it lacks Eq and Ord:
  1. You cannot directly use f32 as a key in a std::collections::HashMap or HashSet.
  2. You cannot use the standard .sort() method on a Vec<f32>. You must use .sort_by() or .sort_unstable_by() with a custom comparator (e.g., f32::total_cmp).

Type Casting

Rust does not perform implicit type coercion. To convert between f32 and other numeric types, you must use the as keyword. Casting from an integer to an f32 may result in precision loss if the integer requires more than 24 bits to represent exactly.
Tired of Poor Rust Skills? Fix That With Deep Grasping!Learn More