ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
### **百分比值(保留2位小数点)** ```go /* * Pct x,y百分比值 * github.com/shopspring/decimal * patterns 百分比模式 * x=2 y=3 * patterns值 默认值:1 * 1(百分制) --> (x/y)*100 (66.666/100)*100 66.66 * 2(四舍五入百分制) --> (x/y)*100(四舍五入) 66.67 * 3(小数制) --> x/y 0.66 * 4(四舍五入小数制) --> x/y(四舍五入) 0.67 */ func Pct(x, y float64, patterns ...int) float64 { if y == 0 { return 0 } pattern := 1 if len(patterns) >= 1 { pattern = patterns[0] } ratio := decimal.NewFromFloat(x).Div(decimal.NewFromFloat(y)) switch pattern { case 1: ratio = ratio.Mul(decimal.NewFromInt(100)).Truncate(2) case 2: ratio = ratio.Mul(decimal.NewFromInt(100)).Round(2) case 3: ratio = ratio.Truncate(2) case 4: ratio = ratio.Round(2) } v, _ := ratio.Float64() return v } ```