Kaynağa Gözat

ccf:兼容解析浮点数字符串

hsun 5 gün önce
ebeveyn
işleme
fd1dff8b72
1 değiştirilmiş dosya ile 25 ekleme ve 20 silme
  1. 25 20
      services/base_from_ccf/common.go

+ 25 - 20
services/base_from_ccf/common.go

@@ -9,6 +9,7 @@ import (
 	"fmt"
 	"io"
 	"log"
+	"math"
 	"mime/multipart"
 	"net/http"
 	"net/url"
@@ -565,34 +566,38 @@ func extractReportPublishTime(text string) (time.Time, error) {
 	return parsedDate, nil
 }
 
-// calculateDataHalfVal 取出数据区间的折中值, 如"7-9天"返回结果为"8"
-func calculateDataHalfVal(duration string) (result string, err error) {
-	re := regexp.MustCompile(`\d+`)
+// calculateDataHalfVal 提取字符串中的两个数字(支持整数和浮点数),计算它们的平均值,并格式化输出
+func calculateDataHalfVal(duration string) (string, error) {
+	// 支持整数和浮点数匹配
+	re := regexp.MustCompile(`\d+(?:\.\d+)?`)
 	matches := re.FindAllString(duration, -1)
 	if len(matches) != 2 {
-		err = fmt.Errorf("未找到两个数字, Num: %d", len(matches))
-		return
+		return "", fmt.Errorf("未找到两个数字: %s", duration)
 	}
 
-	a, e := strconv.Atoi(matches[0])
-	if e != nil {
-		err = e
-		return
+	a, err := strconv.ParseFloat(matches[0], 64)
+	if err != nil {
+		return "", err
 	}
-	b, e := strconv.Atoi(matches[1])
-	if e != nil {
-		err = e
-		return
+	b, err := strconv.ParseFloat(matches[1], 64)
+	if err != nil {
+		return "", err
 	}
-	average := float64(a+b) / 2.0
 
-	// 格式化结果
-	if average == float64(int(average)) {
-		result = strconv.Itoa(int(average))
-	} else {
-		result = fmt.Sprintf("%.1f", average)
+	average := (a + b) / 2.0
+
+	// 四舍五入到两位小数
+	rounded := math.Round(average*100) / 100
+
+	// 使用 Sprintf 自动判断是否显示小数位
+	switch rounded {
+	case math.Trunc(rounded):
+		return fmt.Sprintf("%.0f", rounded), nil
+	case math.Round(rounded*10) / 10:
+		return fmt.Sprintf("%.1f", rounded), nil
+	default:
+		return fmt.Sprintf("%.2f", rounded), nil
 	}
-	return
 }
 
 // gb2312ToPercentEncoding 中文字符转码