增加工具函数

This commit is contained in:
2026-11-26 01:37:52 +08:00
parent 4a4ffeb169
commit 4760ac3687
7 changed files with 85 additions and 6 deletions
+28 -4
View File
@@ -67,15 +67,30 @@ inline std::string operator+(std::string_view a, std::string_view b)
return ret += b;
}
/**
* @brief to_string包装
* @note 小数默认两位
* @brief to_string float包装
* @note 小数默认两位
*/
template<int N = 2, IsFloating T>
std::string to_string(T v)
{
if constexpr (N == 0)
return fmt::format("{:.0f}", v);
else if constexpr (N == 1)
return fmt::format("{:.1f}", v);
else if constexpr (N == 2)
return fmt::format("{:.2f}", v);
else if constexpr (N == 3)
return fmt::format("{:.3f}", v);
else
return std::to_string(v);
}
template<IsFloating T>
std::string to_string(T v, std::string_view fmt = "{:.2f}")
std::string to_string(T v, std::string_view fmt)
{
return fmt::vformat(fmt, fmt::make_format_args(v));
}
//! 默认转换
template<IsBaseNotFloating T>
std::string to_string(T v)
{
@@ -1123,6 +1138,15 @@ Array<std::string, H> FormatString2(const Array2<std::string, W, H>& arr)
*/
std::vector<std::string> FormatString2(const Vector2<std::string>& arr);
/**
* @brief 转为百分比显示
* @note 例如 0.15 -> 15%
*/
inline std::string ToPercent(float k)
{
return std::to_string((int)(k * 100.0f)) + '%';
}
/**
* @brief 返回子串,直到数字(不判断小数点和负号)
* @note 例如:背景音022 -> 背景音
+19
View File
@@ -27,6 +27,7 @@ namespace dl
/**
* @brief 限制数值到 [a, b]
* @note 等价于 std::clamp
*/
template<typename T>
constexpr T clamp(const T& x, const T& a, const T& b)
@@ -37,6 +38,24 @@ constexpr T clamp(const T& x, const T& a, const T& b)
return b;
return x;
}
/**
* @brief 限制数值大于等于0
*/
constexpr float clamp0(float x)
{
if (x < 0)
return 0;
return x;
}
/**
* @brief 限制数值小于等于0
*/
constexpr float clamp0_less(float x)
{
if (x > 0)
return 0;
return x;
}
/**
* @brief 限制数值到 [0, 1]
+17
View File
@@ -241,4 +241,21 @@ std::string_view lang_auto(std::string_view tag_name)
return lang({ tag_name.begin() + 1, tag_name.end() });
}
std::string_view lang_sybmol(std::string_view str)
{
if (g_lang->GetLangCurrent() == Language::E_CHINESE)
{
if (str == ":")
return ":";
}
else
{
if (str == ":")
return ": ";
}
return str;
}
}
+8
View File
@@ -90,6 +90,8 @@ public:
_data.resize(_typeCur);
}
Type GetLangCurrent() { return _typeCur; }
~Language();
using MapName = std::unordered_map<std::string, std::string, string_hash, std::equal_to<>>;
@@ -133,4 +135,10 @@ std::string lang(std::string_view tag_name, Args&& ...args)
return fmt::vformat(lang(tag_name), fmt::make_format_args(args...));
}
/**
* @brief 符号本地化处理
* @note 例如在中文环境下:变为:
*/
std::string_view lang_sybmol(std::string_view str);
}
+11
View File
@@ -79,5 +79,16 @@ private:
void _init();
};
inline std::string ToPercentAutoColor(float fix)
{
if (fix == 0)
return "";
else if (fix > 0)
return fmt::format("[c:green]+{}[c]", String::ToPercent(fix));
else if (fix < 0)
return fmt::format("[c:red]{}[c]", String::ToPercent(fix));
}
}
#endif