rustHow to format float string in Rust
Formatting a float string in Rust can be done using the format!
macro. This macro takes a format string and a list of arguments and returns a String
object. The format string can contain special formatting characters that will be replaced with the corresponding argument.
For example, to format a float string with two decimal places, the following code can be used:
let x = 3.14159;
let formatted_string = format!("{:.2}", x);
println!("{}", formatted_string);
Output
3.14
Explanation:
- The
let x = 3.14159
statement declares a variablex
and assigns it the value3.14159
. - The
let formatted_string = format!("{:.2}", x)
statement uses theformat!
macro to create aString
object with the value3.14
from the floatx
. The{:.2}
part of the format string specifies that the float should be formatted with two decimal places. - The
println!("{}", formatted_string)
statement prints the formatted string to the console.
Helpful links:
More of Rust
- How to get a capture group using Rust regex?
- How to use Unicode in a regex in Rust?
- How to get the last element of a Rust slice?
- How to match the end of a line in a Rust regex?
- How to replace a capture group using Rust regex?
- How to use non-capturing groups in Rust regex?
- How to use an enum in a Rust HashMap?
- How to match whitespace with a regex in Rust?
- How to split a string with Rust regex?
- How to match a URL with a regex in Rust?
See more codes...