#297 Aug 4, 2026

297. signum — The -1 / 0 / +1 You Keep Building With an If-Else Ladder

Every “which direction?” check ends up as the same three-branch ladder: greater, less, equal. signum is that ladder as one method call — with a float twist you need to know about.

The ladder

You want the direction of a difference — for a comparator, a game step, a sort key:

1
2
3
4
5
6
7
8
9
let delta: i32 = -7;

let dir = if delta > 0 {
    1
} else if delta < 0 {
    -1
} else {
    0
};

One call

1
2
3
4
5
let dir = delta.signum(); // -1

assert_eq!(42i32.signum(), 1);
assert_eq!(0i32.signum(), 0);
assert_eq!((-3i64).signum(), -1);

It shines whenever you need to move one step toward a target, whatever the distance:

1
2
3
4
5
6
7
let mut pos: i32 = 3;
let target = 7;

while pos != target {
    pos += (target - pos).signum(); // steps ±1, stops exactly
}
assert_eq!(pos, target);

No overshoot, no separate branches for “target is behind me” — the sign does the steering.

The float trap

f64::signum is not the same function. It reports the sign bit, so zero is never 0.0:

1
2
3
assert_eq!(0.0_f64.signum(), 1.0);    // not 0.0!
assert_eq!((-0.0_f64).signum(), -1.0);
assert!(f64::NAN.signum().is_nan());

If you want the integer-style three-way answer for floats, be explicit about zero:

1
2
3
let x = 0.0_f64;
let dir = if x == 0.0 { 0.0 } else { x.signum() };
assert_eq!(dir, 0.0);

Reach for signum on integers without a second thought; on floats, remember it answers “which sign bit?” — not “is this positive, negative, or zero?”.

← Previous 296. [T; N]::each_ref — Map Over an Array Without Giving It Away Next → 298. copysign — Stamp One Number's Sign Onto Another, Sign Bit and All