From 5405811eaa2af3e84cc3423010488d8429657bb8 Mon Sep 17 00:00:00 2001 From: Sam Anthony Date: Fri, 20 Jan 2023 17:49:23 -0330 Subject: round displacement when converting units --- src/lib.rs | 16 ++++++++++++++++ src/main.rs | 36 ++++++++++++++++++++++++++---------- src/volume.rs | 4 ++-- 3 files changed, 44 insertions(+), 12 deletions(-) (limited to 'src') diff --git a/src/lib.rs b/src/lib.rs index cd3320a..c41b791 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,3 +1,19 @@ pub mod volume; type Percent = u8; + +pub fn round(f: F, digits: I) -> f64 +where + F: Into, + I: Into + 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::().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::().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 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> From for Litre { impl From for Litre { fn from(value: CubicMetre) -> Self { - Self(value.0 * 10_f64.powf(3.)) + Self(value.0 * 10_f64.powi(3)) } } -- cgit v1.2.3