Skip to content

Commit

Permalink
[Units] Simplify Units::str()
Browse files Browse the repository at this point in the history
  • Loading branch information
ischoegl committed Aug 19, 2021
1 parent 5751633 commit 6345889
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 9 deletions.
23 changes: 17 additions & 6 deletions src/base/Units.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -246,19 +246,30 @@ std::string Units::str() const {
{"kmol", m_quantity_dim},
};

std::string num = "";
std::string out = "";
for (auto const& dim : dims) {
int rounded = roundf(dim.second);
if (dim.second == 1.) {
out.append(fmt::format(" * {}", dim.first));
} else if (dim.second == 0.) {
if (dim.second == 0.) {
// skip
} else if (dim.second == 1.) {
num.append(fmt::format(" * {}", dim.first));
} else if (dim.second == -1.) {
out.append(fmt::format(" / {}", dim.first));
} else if (dim.second == rounded && rounded > 0) {
num.append(fmt::format(" * {}^{}", dim.first, rounded));
} else if (dim.second == rounded) {
out.append(fmt::format(" * {}^{}", dim.first, rounded));
out.append(fmt::format(" / {}^{}", dim.first, -rounded));
} else if (dim.second > 0) {
num.append(fmt::format(" * {}^{}", dim.first, dim.second));
} else {
out.append(fmt::format(" * {}^{}", dim.first, dim.second));
out.append(fmt::format(" / {}^{}", dim.first, -dim.second));
}
}
if (num.size()) {
// concatenate numerator and denominator (skipping leading '*')
out = fmt::format("{}{}", num.substr(2), out);
}

std::string factor;
if (m_factor == roundf(m_factor)) {
Expand All @@ -269,7 +280,7 @@ std::string Units::str() const {
}

if (out.size()) {
return fmt::format("{} {}", factor, out.substr(3));
return fmt::format("{}{}", factor, out);
}
return factor;
}
Expand Down
6 changes: 3 additions & 3 deletions test/general/test_units.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ TEST(Units, from_string) {
EXPECT_EQ(Units("2").str(), "2.0");
EXPECT_EQ(Units("kg").str(), "1.0 kg");
EXPECT_EQ(Units("1.0 kg^0.5").str(), "1.0 kg^0.5");
EXPECT_EQ(Units("kg / m^3").str(), "1.0 kg * m^-3");
EXPECT_EQ(Units("kg / m^3").str(), "1.0 kg / m^3");
EXPECT_EQ(Units("0.001 m^3").str(), "0.001 m^3");
}

Expand All @@ -19,8 +19,8 @@ TEST(Units, copy_construct) {
EXPECT_EQ(Units(Units(1., 1.)).str(), "1.0 kg");
EXPECT_EQ(Units(Units(1., 2.)).str(), "1.0 kg^2");
EXPECT_EQ(Units(Units(1., .5)).str(), "1.0 kg^0.5");
EXPECT_EQ(Units(Units(1., -1.)).str(), "1.0 kg^-1");
EXPECT_EQ(Units(Units(1., 1., -3.)).str(), "1.0 kg * m^-3");
EXPECT_EQ(Units(Units(1., -1.)).str(), "1.0 / kg");
EXPECT_EQ(Units(Units(1., 1., -3.)).str(), "1.0 kg / m^3");
EXPECT_EQ(Units(Units(.001, 0., 3.)).str(), "0.001 m^3");
}

Expand Down

0 comments on commit 6345889

Please sign in to comment.