93 lines
2.6 KiB
C++
93 lines
2.6 KiB
C++
/*
|
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
*/
|
|
|
|
#include "UnitFormatter.hpp"
|
|
#include <string>
|
|
#include <sstream>
|
|
#include <iomanip>
|
|
|
|
namespace
|
|
{
|
|
template<typename T> std::string FormatValue(T value, int precision, bool trimTrailingZeros = false)
|
|
{
|
|
std::ostringstream out;
|
|
out << std::fixed << std::setprecision(precision) << value;
|
|
std::string result = out.str();
|
|
|
|
if (trimTrailingZeros && result.find('.') != std::string::npos)
|
|
{
|
|
result.erase(result.find_last_not_of('0') + 1);
|
|
|
|
if (result.back() == '.')
|
|
{
|
|
result.pop_back();
|
|
}
|
|
}
|
|
|
|
return result;
|
|
}
|
|
}
|
|
|
|
namespace OpenVulkano
|
|
{
|
|
UnitFormatter::UnitFormatter(bool useMetric, int precisionDigits, bool doTrimTrailingZeros)
|
|
: metric(useMetric), precision(precisionDigits), trimTrailingZeros(doTrimTrailingZeros)
|
|
{
|
|
}
|
|
|
|
std::string UnitFormatter::Format(units::length::meter_t distance)
|
|
{
|
|
if (metric)
|
|
{
|
|
if (distance > units::length::meter_t(0) && distance < units::length::meter_t(0.1))
|
|
{
|
|
return FormatValue(units::length::millimeter_t(distance).value(), precision, trimTrailingZeros) + " mm";
|
|
}
|
|
else if (distance >= units::length::kilometer_t(1))
|
|
{
|
|
return FormatValue(units::length::kilometer_t(distance).value(), precision, trimTrailingZeros) + " km";
|
|
}
|
|
return FormatValue(distance.value(), precision, trimTrailingZeros) + " m";
|
|
}
|
|
else
|
|
{
|
|
auto distanceFeet = units::length::foot_t(distance).value();
|
|
auto distanceInches = units::length::inch_t(distance).value();
|
|
|
|
if (distanceFeet > 0 && distanceFeet < 0.1)
|
|
{
|
|
return FormatValue(distanceInches, precision, trimTrailingZeros) + " in";
|
|
}
|
|
else if (distanceFeet >= 5280.0)
|
|
{
|
|
return FormatValue(units::length::mile_t(distance).value(), precision, trimTrailingZeros) + " mi";
|
|
}
|
|
return FormatValue(distanceFeet, precision, trimTrailingZeros) + " ft";
|
|
}
|
|
}
|
|
|
|
std::string UnitFormatter::Format(units::area::square_meter_t area)
|
|
{
|
|
if (metric)
|
|
{
|
|
if (area >= units::area::square_kilometer_t(1))
|
|
{
|
|
return FormatValue(units::area::square_kilometer_t(area).value(), precision, trimTrailingZeros)
|
|
+ " km²";
|
|
}
|
|
return FormatValue(area.value(), precision, trimTrailingZeros) + " m²";
|
|
}
|
|
else
|
|
{
|
|
auto areaSquareFeet = units::area::square_foot_t(area).value();
|
|
if (areaSquareFeet >= 27878400.0)
|
|
{
|
|
return FormatValue(units::area::square_mile_t(area).value(), precision, trimTrailingZeros) + " mi²";
|
|
}
|
|
return FormatValue(areaSquareFeet, precision, trimTrailingZeros) + " ft²";
|
|
}
|
|
}
|
|
} |