The OrderedFloat<T> struct is a wrapper around floating-point types (like f32 or f64) that provides implementations for Eq, Ord, and Hash. This allows floats to be used in collections that require total ordering, such as HashSet, HashMap, BTreeMap, or BTreeSet.
Ordering Behavior
Unlike the standard IEEE floating-point behavior, OrderedFloat treats NaN as greater than all other values and equal to itself.
Equality Nuances
-0.0 and +0.0 are considered equal.- All
NaN values are considered equal, regardless of their underlying bit representation (sign, payload, etc.).
Because of these equality rules, OrderedFloat might not be suitable for interning or memoization where bit-perfect identity is required, unless values are canonicalized before insertion.
use ordered_float::OrderedFloat;
use std::f32::NAN;
// Sorting a list containing NaN
let mut v = [OrderedFloat(NAN), OrderedFloat(2.0), OrderedFloat(1.0)];
v.sort();
assert_eq!(v, [OrderedFloat(1.0), OrderedFloat(2.0), OrderedFloat(NAN)]);
// Using as a key in a HashSet
let mut s = std::collections::HashSet::new();
s.insert(OrderedFloat(NAN));
assert!(s.contains(&OrderedFloat(NAN)));