How to print any float number with point?


#1

If i write this:

let x: f32 = 10.0;
println!(“let x: f32 = {}”, x);

I get a string
let x: f32 = 10

But i want to output 10.0 (with point!!!)
I need it for rust codegen. But this is not a valid rust code.

https://play.rust-lang.org/?gist=25697a7bcce92b07b51cbfb58435fb7c&version=stable&backtrace=0


#2
println!("let x: f32 = {:.1}", x};

For details, check out std::fmt


#3

This cut precision to 1.
I need a more general method because i need to generate rs file with array of floats
for example:

static A: [f32; 5] = [1.0, 2.01, 3.57656, 4.0, 5.55435];


#4

I don’t know an answer to your exact question. But perhaps your requirement is satisfied by the following statement:
println!("let x = {}f32", x);


#5

Thanks!


#6

Does this statement really work ?
I cannot find a better way to deal with your requirement, here are two alternative ways:


#7

Yes - this is exactly what i need.
Thanks!


#8

Relative question:
How i can print float in this form 1.0e-40 ?


#9

Check out dtoa which serde_json uses for printing floating point numbers in e-notation.

extern crate dtoa;

use std::io;

fn main() {
    print!("let x = ");
    dtoa::write(io::stdout(), 1e-40).unwrap();
}

#10

I found that format!("{:e}", 0.111) do the job