1
0
Fork 0

Add formatters for percentages

This commit is contained in:
Robbert van der Helm 2022-03-08 18:43:57 +01:00
parent 24f3593de0
commit 2c6f65a342
2 changed files with 20 additions and 1 deletions

View file

@ -211,7 +211,8 @@ impl DiopserParams {
FloatRange::Linear { min: 0.0, max: 1.0 },
)
.with_unit("%")
.with_value_to_string(Arc::new(|value| format!("{:.0}", value * 100.0))),
.with_value_to_string(formatters::f32_percentage(0))
.with_string_to_value(formatters::from_f32_percentage()),
}
}
}

View file

@ -7,6 +7,24 @@ pub fn f32_rounded(digits: usize) -> Arc<dyn Fn(f32) -> String + Send + Sync> {
Arc::new(move |x| format!("{:.digits$}", x))
}
/// Format a `[0, 1]` number as a percentage. Does not include the percent sign, you should specify
/// this as the parameter's unit.
pub fn f32_percentage(digits: usize) -> Arc<dyn Fn(f32) -> String + Send + Sync> {
Arc::new(move |value| format!("{:.digits$}", value * 100.0))
}
/// Parse a `[0, 100]` percentage to a `[0, 1]` number. Handles the percentage unit for you. Used in
/// conjunction with [`f32_percentage`].
pub fn from_f32_percentage() -> Arc<dyn Fn(&str) -> Option<f32> + Send + Sync> {
Arc::new(|string| {
string
.trim_end_matches(&[' ', '%'])
.parse()
.ok()
.map(|x: f32| x / 100.0)
})
}
/// Format an order/power of two. Useful in conjunction with [`from_power_of_two()`] to limit
/// integer parameter ranges to be only powers of two.
pub fn i32_power_of_two() -> Arc<dyn Fn(i32) -> String + Send + Sync> {