Consider 2 f32 numbers in Rust, like the values 2.1 and 5.0. With some logic, we can convert this is into a percentage like 42%.
Often when computing percentages, we want to round them as well. The round()
function on f32 can be helpful here. We also must first multiply by 100.0.
To begin, we introduce 2 custom Rust functions to help with computing percentages. The get_percentage()
and get_percentage_rounded
functions implement the logic.
get_percentage
function—these are divided to get a ratio.get_percentage_rounded
version is the same as get_percentage()
but calls round()
for a result that is easier to display.fn get_percentage(x: f32, y: f32) -> String { // Convert to percentage string. let result = (x * 100.0) / y; return format!("{}%", result); } fn get_percentage_rounded(x: f32, y: f32) -> String { // Convert to rounded percentage string. let result = (x * 100.0) / y; let rounded = result.round(); return format!("{}%", rounded); } fn main() { // Test the percentage functions. let percentage1 = get_percentage(5.0, 2.0); println!("{}", percentage1); let percentage2 = get_percentage(2.1, 5.0); println!("{}", percentage2); let percentage3 = get_percentage_rounded(2.1, 5.0); println!("{}", percentage3); }250% 41.999996% 42%
To create a string
containing the end percentage sign, we use the "format!" macro. This is similar to the "println
!" macro, but returns a String
.
It is important to use a floating-point type like f32 to compute percentages. With i32
division, the result is truncated to fit in an integer.
With these helpful functions, we can go from 2 f32 numbers to a nicely-formatted percentage string
. The result is like 42%, and can even be rounded.