Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep a trailing zero when printing a float without setting precision?

Given a whole floating point number, Rust does not include any decimals when converting it to a string. I want a way to keep the .0 around without setting a fixed precision since I like the default formatting for numbers that do have decimals (playground):

fn main() {
    println!("{}", 1.0);
    println!("{}", 1.1999999);
    println!("{:.1}", 1.0);
    println!("{:.1}", 1.999999)
}
1
1.1999999
1.0
2.0

So I would like to be able to print that extra .0 without it affecting anything else.

like image 511
m0meni Avatar asked May 09 '26 08:05

m0meni


1 Answers

A way to keep the additional .0, differentiating it from an integer, is to use the Debug formatter:

println!("{:?}", 1.0);
println!("{:?}", 1.1999999);
1.0
1.1999999

I don't see a way to dictate this behavior with the precision format specifier since providing a precision uses that as an "exact" precision, and without it internally uses a "min" precision of 0 and 1 for Display and Debug respectively. (source)

like image 88
kmdreko Avatar answered May 12 '26 15:05

kmdreko