From: Andreas Sandberg Date: Thu, 3 Oct 2024 16:35:53 +0000 (+0100) Subject: strutil: Add a atof variant that determines precision X-Git-Url: https://sigrok.org/gitaction?a=commitdiff_plain;h=e6fcb482ad22bb5671bdc95ec742591d2fa684fe;p=libsigrok.git strutil: Add a atof variant that determines precision There is already a helper to convert a string to a double and determine its precision. Add a helper that does this for floats as well. Signed-off-by: Andreas Sandberg --- diff --git a/src/libsigrok-internal.h b/src/libsigrok-internal.h index fe2ac520..8d509eba 100644 --- a/src/libsigrok-internal.h +++ b/src/libsigrok-internal.h @@ -2003,6 +2003,7 @@ SR_PRIV int sr_atof(const char *str, float *ret); SR_PRIV int sr_atod_ascii(const char *str, double *ret); SR_PRIV int sr_atod_ascii_digits(const char *str, double *ret, int *digits); SR_PRIV int sr_atof_ascii(const char *str, float *ret); +SR_PRIV int sr_atof_ascii_digits(const char *str, float *ret, int *digits); SR_PRIV int sr_count_digits(const char *str, int *digits); diff --git a/src/strutil.c b/src/strutil.c index 2cc20575..5e941e91 100644 --- a/src/strutil.c +++ b/src/strutil.c @@ -397,6 +397,33 @@ SR_PRIV int sr_atof_ascii(const char *str, float *ret) return SR_OK; } +/** + * Convert text to a floating point value, and get its precision. + * + * @param[in] str The input text to convert. + * @param[out] ret The conversion result, a double precision float number. + * @param[out] digits The number of significant decimals. + * + * @returns SR_OK in case of successful text to number conversion. + * @returns SR_ERR when conversion fails. + */ +SR_PRIV int sr_atof_ascii_digits(const char *str, float *ret, int *digits) +{ + int d; + float f; + + if (sr_count_digits(str, &d) != SR_OK || sr_atof_ascii(str, &f) != SR_OK) + return SR_ERR; + + if (ret) + *ret = f; + + if (digits) + *digits = d; + + return SR_OK; +} + /** * Get the precision of a floating point number. *