In this post, let us explore different ways to format integers, decimal, strings using format specifiers
Formatting Integers
Just to format integers as it-is, we have to pass integers as argument to format macro
println!("{}", format!("{}", 100));
To zero-pad integers with specific number of digits, in the format macro, specify the length. In this below example, we'll have zero-padded integer with max 10 digits
println!("{}", format!("{:010}", 5));
Convert number into binary-formatted, just specify #b
in format macro as below
println!("{}", format!("{:#b}", 50));
Convert number into octal-formatted, just specify #o
in format macro as below
println!("{}", format!("{:#o}", 50));
Convert number into hex-formatted, just specify #x
or #X
in format macro as below
println!("{}", format!("{:#x}", 50));
If you would like to have 1000 specifier as per locale, it can be achieved using num_format
crate. The below example, will format the number 1 billion in US locale
println!("{}", 1_000_000_000.to_formatted_string(&num_format::Locale::en));
Formatting the number 1 billion in French locale
println!("{}", 1_000_000_000.to_formatted_string(&num_format::Locale::fr));
Formatting the number 1 billion in Indian locale
println!("{}", 1_000_000_000.to_formatted_string(&num_format::Locale::en_IN));
Formatting Decimals
To format decimal numbers with specific precision, we can use below specifiers
println!("{}", format!("{:.5}", 100.02));
In case if the decimal number exceeds the given precision, the number will get rounded-off at nth precision. The below code outputs 100.02782
println!("{}", format!("{:.5}", 100.02781839));
Formatting String
To format string in left-aligned, we can use below specifier in the macro
println!("{}", format!("{:<20}", "Rust is awesome"));
To align string in center within given length, we can use below specifier in the macro
println!("{}", format!("{:^20}", "Rust is awesome"));
To right-align string within given length, we can use below specifier in the macro
println!("{}", format!("{:>20}", "Rust is awesome"));
In case if you would like to fill the white-space with specific character, we just need to specify the specific character before the respective symbol (^, >, <) in the specifier
println!("{}", format!("{:*^20}", "Rust is awesome"));
We can use the above specifiers to align integers as well.
All the code examples can be found in this link
Please feel free to share your feedback.
Happy reading!!!
Top comments (0)