From 5bdbe2a2e2e74e76de24153081d93393f9f72283 Mon Sep 17 00:00:00 2001 From: KiddoV Date: Tue, 2 Jul 2024 02:08:39 -0500 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat:=20support=20convert=20float?= =?UTF-8?q?=20string=20to=20int=20(#180)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * support convert float string to int * use `math.Round` for more natural int --- mathutil/convert.go | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/mathutil/convert.go b/mathutil/convert.go index 0369519f2..0d80d330b 100644 --- a/mathutil/convert.go +++ b/mathutil/convert.go @@ -192,7 +192,14 @@ func ToIntWith(in any, optFns ...ConvOptionFn[int]) (iVal int, err error) { iVal = int(tVal) } case string: - iVal, err = strconv.Atoi(strings.TrimSpace(tVal)) + if iVal, err = strconv.Atoi(strings.TrimSpace(tVal)); err != nil { + // handle the case where the string might be a float + var floatVal float64 + if floatVal, err = strconv.ParseFloat(strings.TrimSpace(tVal), 64); err == nil { + iVal = int(math.Round(floatVal)) + err = nil + } + } case comdef.Int64able: // eg: json.Number var i64 int64 if i64, err = tVal.Int64(); err == nil {