Improved unit printing

pull/2/head
Mark 2023-04-08 20:48:49 -07:00
parent e9d4ec0b12
commit d4b7f5b078
Signed by: Mark
GPG Key ID: AD62BB059C2AAEE4
2 changed files with 33 additions and 2 deletions

View File

@ -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;
}
}

View File

@ -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}
}
}