aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorSam Anthony <sam@samanthony.xyz>2023-01-20 17:49:23 -0330
committerSam Anthony <sam@samanthony.xyz>2023-01-20 17:49:23 -0330
commit5405811eaa2af3e84cc3423010488d8429657bb8 (patch)
treed74df7e2c498e0db5b2b045444656026e14488a8
parent4efbba96bbdf3dddeb0a853310b08a5281d2f8a0 (diff)
downloadvolute-5405811eaa2af3e84cc3423010488d8429657bb8.zip
round displacement when converting units
-rw-r--r--src/lib.rs16
-rw-r--r--src/main.rs36
-rw-r--r--src/volume.rs4
3 files changed, 44 insertions, 12 deletions
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, 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))
}
}