Float Rounding Half Away From Zero
Compare f64 round, floor, ceil, and trunc on negative values, then use round_ties_even when banking-style halves are required.
Code
fn main() {
let values = [2.5_f64, -2.5, 2.4, -2.4];
for v in values {
// round 半数远离零,floor 向负无穷,ceil 向正无穷,trunc 向零
println!(
"{v:>5} round={:>4} floor={:>4} ceil={:>4} trunc={:>4}",
v.round(),
v.floor(),
v.ceil(),
v.trunc()
);
}
// round_ties_even:半数取偶(银行家舍入)
println!(
"ties even: {} {} {}",
2.5_f64.round_ties_even(),
3.5_f64.round_ties_even(),
2.5_f64.round()
);
// fract 取小数部分 self - self.trunc(),符号跟随原值
println!("fract: {} {}", 2.75_f64.fract(), (-2.75_f64).fract());
}Four rounding rules at work
Structurally, expect the function main and nothing else.
Iteration happens inside for v in values — everything outside it runs once.
Caveats
- No external code is referenced; plain f64 methods make up the whole demo.
Putting it to use
Entry signature: fn main()
The run prints ties even:, fract: — each prefix names the step that produced it.
Method calls under test
let values = [2.5_f64, -2.5, 2.4, -2.4];
2.5_f64.round()
);
Interactive Tools for This Topic
FAQ
- What does Float Rounding Half Away From Zero print when run?
- Run it as a complete program — the output lines carry labels such as `ties even:`, `fract:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.