From 26aa717e0c2db8507912162ca559ced7126fdcb3 Mon Sep 17 00:00:00 2001 From: wood chen Date: Sun, 1 Jun 2025 03:48:07 +0800 Subject: [PATCH] =?UTF-8?q?refactor(price=5Frates.go):=20=E4=BC=98?= =?UTF-8?q?=E5=8C=96=E5=9B=9B=E8=88=8D=E4=BA=94=E5=85=A5=E5=87=BD=E6=95=B0?= =?UTF-8?q?=EF=BC=8C=E7=A1=AE=E4=BF=9D=E7=B2=BE=E7=A1=AE=E8=AE=A1=E7=AE=97?= =?UTF-8?q?=E5=B9=B6=E7=A7=BB=E9=99=A4=E5=86=97=E4=BD=99=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/handlers/one_hub/price_rates.go | 24 ++++++++++++++---------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/backend/handlers/one_hub/price_rates.go b/backend/handlers/one_hub/price_rates.go index 5cd7ae1..46ba9b5 100644 --- a/backend/handlers/one_hub/price_rates.go +++ b/backend/handlers/one_hub/price_rates.go @@ -1,6 +1,7 @@ package one_hub import ( + "math" "net/http" "strings" "time" @@ -49,13 +50,25 @@ var extraRelativeToInput = map[string]bool{ "output_image_tokens": false, } +// round 四舍五入到指定小数位,使用 math 包提供精确计算 +func round(num float64, precision int) float64 { + if precision < 0 { + return num + } + // 使用 math.Pow 计算倍数,避免循环累积误差 + multiplier := math.Pow(10, float64(precision)) + // 使用 math.Round 进行精确四舍五入 + return math.Round(num*multiplier) / multiplier +} + // 计算安全倍率,避免除以零 func calculateSafeRatio(value, baseRate float64) float64 { // 如果基准率为0或接近0,返回1作为默认倍率 if baseRate < 0.0000001 { return 1.0 // 如果基准率接近0,返回1作为默认倍率 } - return value / baseRate + // 计算倍率并四舍五入到4位小数 + return round(value/baseRate, 4) } // GetPriceRates 获取价格倍率 @@ -635,12 +648,3 @@ func ClearRatesCache() { database.GlobalCache.Delete("one_hub_price_rates") database.GlobalCache.Delete("one_hub_official_price_rates") } - -// round 四舍五入到指定小数位 -func round(num float64, precision int) float64 { - precision10 := float64(1) - for i := 0; i < precision; i++ { - precision10 *= 10 - } - return float64(int(num*precision10+0.5)) / precision10 -}