rust convert floating point number, to a string, with decimal digits.
To convert a floating-point number to a string with decimal digits in Rust, you can use the to_string
method provided by the ToString
trait. Here's an example:
fn main() {
let number = 3.14;
let number_string = number.to_string();
println!("{}", number_string);
}
This code will output the string representation of the floating-point number 3.14
. You can customize the number of decimal places by using the format!
macro with the {:.N}
format specifier, where N
is the desired number of decimal places. Here's an example:
fn main() {
let number = 3.14159265359;
let number_string = format!("{:.2}", number);
println!("{}", number_string);
}
This code will output the string representation of the floating-point number 3.14159265359
with 2 decimal places, resulting in "3.14"
.