Get Percentage
This page was last reviewed on Jun 21, 2023.
Dot Net Perls
Percentage. 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%.
Some details. 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.
Example code. To begin, we introduce 2 custom Rust functions to help with computing percentages. The get_percentage() and get_percentage_rounded functions implement the logic.
Start We pass 2 arguments to the get_percentage function—these are divided to get a ratio.
Next We first compute a ratio and multiply it by 100.0. We use f32 to losing data after the decimal place.
Finally The 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%
Format notes. 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.
Type notes. 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.
A summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jun 21, 2023 (edit).
© 2007-2024 Sam Allen.