Format Floats With Precision And Signs
Fix decimal places with {:.N}, force signs, zero-pad widths, and switch to scientific notation with {:e} and {:E} format specifiers.
Code
fn main() {
let ratio = 2.0_f64 / 3.0;
let price = 1234.5_f64;
// {:.N} 固定 N 位小数(四舍五入,不补零到宽度)
println!("{:.3}", ratio);
println!("{:.0}", ratio);
// + 号强制显式 signs;08.2 用零填充到宽度 8;>10.2 右对齐
println!("{:+.2}", ratio);
println!("{:08.2}", price);
println!("{:>10.2}", price);
// {:e} 科学计数法;{:E} 用大写 E
println!("{:e}", 12345.678);
println!("{:E}", 0.000123);
// {:?} Debug 格式保留完整精度
println!("{:?}", ratio);
}How the snippet works
Format Floats With Precision And Signs reduces to the function main.
ratio is 2.0_f64 / 3.0; {:.3} and {:.0} fix decimal places with rounding, {:+.2} forces an explicit sign, {:08.2} zero-pads to width 8, and {:>10.2} right-aligns within width 10. {:e} and {:E} switch to scientific notation with a lower- or upper-case exponent marker. {:?} prints the Debug form, which keeps f64’s full precision instead of a fixed digit count.
Key statements
let ratio = 2.0_f64 / 3.0;
let price = 1234.5_f64;
Interactive Tools for This Topic
Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.Indentation ConverterConvert leading indentation between tabs and spaces at a chosen width, leaving inner content untouched.JSON Formatter & ValidatorFormat, beautify, and validate JSON data with configurable indentation. Instantly catches syntax errors and displays a pretty-printed tree structure.JSON SorterSort JSON object keys by code point ascending or descending, recursively or top-level only, preserving array order.
FAQ
- How do you run Format Floats With Precision And Signs?
- This is a complete program, not a library excerpt — execution starts at the top.
Report a problem with this exampleOpens a pre-filled issue on GitHub.