From d4b7f5b0781ae39314323beb7e91b25f34db3b91 Mon Sep 17 00:00:00 2001 From: Mark Date: Sat, 8 Apr 2023 20:48:49 -0700 Subject: [PATCH] Improved unit printing --- src/quantity/quantity.rs | 4 +++- src/quantity/unit.rs | 31 ++++++++++++++++++++++++++++++- 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/src/quantity/quantity.rs b/src/quantity/quantity.rs index 2ebf01f..90e3d7e 100644 --- a/src/quantity/quantity.rs +++ b/src/quantity/quantity.rs @@ -26,9 +26,11 @@ pub struct Quantity { impl ToString for Quantity { fn to_string(&self) -> String { let mut n = self.v.to_string(); + if self.unitless() { return n; } + n.push(' '); n.push_str(&self.u.to_string()); - n + return n; } } diff --git a/src/quantity/unit.rs b/src/quantity/unit.rs index 3a997a5..da92019 100644 --- a/src/quantity/unit.rs +++ b/src/quantity/unit.rs @@ -30,7 +30,36 @@ pub struct Unit { impl ToString for Unit { fn to_string(&self) -> String { - format!("{:?}", self) + if self.unitless() { return String::new(); }; + + let mut t = String::new(); + let mut b = String::new(); + + for (u, p) in &self.val { + let c = match u { + BaseUnit::Second => "s", + BaseUnit::Meter => "m", + BaseUnit::Kilogram => "kg", + BaseUnit::Ampere => "a", + BaseUnit::Kelvin => "k", + BaseUnit::Mole => "mol", + BaseUnit::Candela => "c" + }; + + if *p == 1f64 { + t.push_str(&format!("{c}")); + } else if *p == -1f64 { + b.push_str(&format!("{c}")); + } else if *p > 0f64 { + t.push_str(&format!("{c}^{p}")); + } else { + b.push_str(&format!("{c}^{}", -p)); + } + }; + + if b.len() != 0 { + format!("{t}/{b}") + } else {t} } }