Skip to content

Commit

Permalink
Better reciprocal unit formatting (Fixes #91)
Browse files Browse the repository at this point in the history
  • Loading branch information
tiffany352 committed Oct 31, 2021
1 parent 61814ee commit aa30306
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
12 changes: 11 additions & 1 deletion core/src/number.rs
Original file line number Diff line number Diff line change
Expand Up @@ -379,6 +379,7 @@ impl<'a> NumberPartsFmt<'a> {

let parts = self.number;

let mut last_was_ws = true;
for tok in parse_pattern(self.pattern) {
match tok {
PatternToken::Exact => {
Expand Down Expand Up @@ -419,6 +420,7 @@ impl<'a> NumberPartsFmt<'a> {
tokens.push(Span::plain("* "));
tokens.push(Span::number(f));
tokens.push(Span::plain(" "));
last_was_ws = true;
}
let mut first = true;
for (dim, &exp) in unit {
Expand All @@ -434,10 +436,15 @@ impl<'a> NumberPartsFmt<'a> {
if exp != 1 {
tokens.push(Span::pow(format!("^{}", exp)));
}
last_was_ws = false;
}
}
if !frac.is_empty() || parts.divfactor.is_some() {
tokens.push(Span::plain(" /"));
if last_was_ws {
tokens.push(Span::plain("/"));
} else {
tokens.push(Span::plain(" /"));
}
if let Some(ref d) = parts.divfactor {
tokens.push(Span::plain(" "));
tokens.push(Span::number(d));
Expand Down Expand Up @@ -536,11 +543,14 @@ impl<'a> NumberPartsFmt<'a> {
},
PatternToken::Whitespace => {
tokens.push(Span::plain(" "));
last_was_ws = true;
continue;
}
PatternToken::Passthrough(text) => {
tokens.push(Span::plain(text));
}
}
last_was_ws = false;
}
// Remove trailing whitespace
loop {
Expand Down
7 changes: 7 additions & 0 deletions core/tests/spans.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,10 @@ fn correct_whitespace() {
test("m s", "1 meter second");
test("kg m / s", "1 kilogram meter / second (impulse)");
}

#[test]
fn correct_reciprocal_units() {
test("1 mpg", "approx. 425143.7 / meter^2 (fuel_efficiency)");
test("1 Hz", "1 / second (frequency)");
test("1 GHz", "1.0e9 / second (frequency)");
}

0 comments on commit aa30306

Please sign in to comment.