diff options
| -rw-r--r-- | src/lib.rs | 16 | ||||
| -rw-r--r-- | src/main.rs | 36 | ||||
| -rw-r--r-- | src/volume.rs | 4 |
3 files changed, 44 insertions, 12 deletions
@@ -1,3 +1,19 @@ pub mod volume; type Percent = u8; + +pub fn round<F, I>(f: F, digits: I) -> f64 +where + F: Into<f64>, + I: Into<i32> + Copy, +{ + (f.into() * 10_f64.powi(digits.into())).round() / 10_f64.powi(digits.into()) +} + +#[cfg(test)] +mod tests { + #[test] + fn round() { + assert_eq!(super::round(0.123456789, 3), 0.123); + } +} diff --git a/src/main.rs b/src/main.rs index 4c6cf43..aabef0a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -3,7 +3,12 @@ use iced::{ Element, Sandbox, Settings, }; -use volute::volume::{self, CubicMetre}; +use volute::{ + round, + volume::{self, CubicMetre}, +}; + +const DECIMAL_DIGITS: i8 = 4; pub fn main() -> iced::Result { App::run(Settings::default()) @@ -33,6 +38,25 @@ impl App { } } +impl UI { + fn convert_displacement(&mut self, unit: volume::Unit) { + if self.displacement.len() > 0 { + self.displacement = format!( + "{}", + round( + volume::convert( + self.displacement.parse::<f64>().unwrap(), + self.displacement_unit, + unit, + ), + DECIMAL_DIGITS, + ), + ); + } + self.displacement_unit = unit; + } +} + impl Sandbox for App { type Message = Message; @@ -50,15 +74,7 @@ impl Sandbox for App { self.set_displacement(&displacement); } Message::DisplacementUnit(unit) => { - self.ui.displacement = format!( - "{:.2}", - volume::convert( - self.ui.displacement.parse::<f64>().unwrap(), - self.ui.displacement_unit, - unit, - ) - ); - self.ui.displacement_unit = unit; + self.ui.convert_displacement(unit); } } } diff --git a/src/volume.rs b/src/volume.rs index 933ae49..5818ea4 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -41,7 +41,7 @@ impl CubicMetre { impl From<Litre> for CubicMetre { fn from(value: Litre) -> Self { - Self(value.0 * 10_f64.powf(-3.)) + Self(value.0 * 10_f64.powi(-3)) } } @@ -56,7 +56,7 @@ impl<F: Into<f64>> From<F> for Litre { impl From<CubicMetre> for Litre { fn from(value: CubicMetre) -> Self { - Self(value.0 * 10_f64.powf(3.)) + Self(value.0 * 10_f64.powi(3)) } } |