summaryrefslogtreecommitdiffstats
path: root/common
diff options
context:
space:
mode:
authorKacper Michajłow <kasper93@gmail.com>2023-11-19 21:22:24 +0100
committerKacper Michajłow <kasper93@gmail.com>2024-03-21 03:50:11 +0100
commit8708f4dc918b1bc005149c50abb3d54d66ed3047 (patch)
treea542bb97e54ba7f6287c755ece5fe1d73bd4b910 /common
parentc84bb1ce67f2dd3adb974c49a66d28c0cf55d39d (diff)
downloadmpv-8708f4dc918b1bc005149c50abb3d54d66ed3047.tar.bz2
mpv-8708f4dc918b1bc005149c50abb3d54d66ed3047.tar.xz
m_property: add `>` for fixed precision floating-point expansion
This enhancement makes it easier to create constant width property expansions, useful for the `--term-status-msg`. Additionally, it changes to `%f` printing with manual zero trimming, which is easier to control than `%g`. With this method, we can directly specify precision, not just significant numbers. This approach also avoids overly high precision for values less than 1, which is not necessary for a generic floating-point print function. A new print helper function is added, which can be used with adjusted precision for specific cases where a different default is needed. This also unifies the code slightly.
Diffstat (limited to 'common')
-rw-r--r--common/common.c19
-rw-r--r--common/common.h6
2 files changed, 25 insertions, 0 deletions
diff --git a/common/common.c b/common/common.c
index 9f8230fbff..7089a6674b 100644
--- a/common/common.c
+++ b/common/common.c
@@ -94,6 +94,25 @@ char *mp_format_time(double time, bool fractions)
return mp_format_time_fmt(fractions ? "%H:%M:%S.%T" : "%H:%M:%S", time);
}
+char *mp_format_double(void *talloc_ctx, double val, int precision,
+ bool plus_sign, bool percent_sign, bool trim)
+{
+ bstr str = {0};
+ const char *fmt = plus_sign ? "%+.*f" : "%.*f";
+ bstr_xappend_asprintf(talloc_ctx, &str, fmt, precision, val);
+ size_t pos = str.len;
+ if (trim) {
+ while (--pos && str.start[pos] == '0')
+ str.len--;
+ if (str.start[pos] == '.')
+ str.len--;
+ }
+ if (percent_sign)
+ bstr_xappend(talloc_ctx, &str, bstr0("%"));
+ str.start[str.len] = '\0';
+ return str.start;
+}
+
// Set rc to the union of rc and rc2
void mp_rect_union(struct mp_rect *rc, const struct mp_rect *rc2)
{
diff --git a/common/common.h b/common/common.h
index ccdd94bba9..cd9bea93c2 100644
--- a/common/common.h
+++ b/common/common.h
@@ -99,6 +99,12 @@ extern const char mpv_copyright[];
char *mp_format_time(double time, bool fractions);
char *mp_format_time_fmt(const char *fmt, double time);
+// Formats a double value to a string with the specified precision.
+// Trailing zeros (and the dot) can be trimmed.
+// Optionally, a plus sign and a percent sign can be added.
+char *mp_format_double(void *talloc_ctx, double val, int precision,
+ bool plus_sign, bool percent_sign, bool trim);
+
struct mp_rect {
int x0, y0;
int x1, y1;