我需要一种算法来计算给定整数和小数位的浮点数。
这里有几个例子来理解我的意思:
Amount
=484, DecimalPlaces
=0 应该返回“484”Amount
=484, DecimalPlaces
=1 应该返回“48.4”Amount
=484, DecimalPlaces
=2 应该返回“4.84”Amount
=484, DecimalPlaces
=3 应该返回“0.484”Amount
=484, DecimalPlaces
=4 应该返回“0.0484”Amount
=484, DecimalPlaces
=5 应该返回“0.00484”我已经有了一个算法,但我不知道如何解决前导零部分。
这是我的方法(我正在使用 golang btw):
func GetAmount(amount, places int) string {
runes := []rune(strconv.Itoa(amount))
result := ""
for j := len(runes) - 1; j >= 0; j-- {
result = string(runes[j]) + result
if j == len(runes)-places {
result = "." + result
}
}
return result
}
提前致谢!
可能不是最有效的,但这里有一个单行:
func GetAmount(amount, places int) string {
return fmt.Sprintf("%.*f", places, float64(amount)/math.Pow10(places))
}
https://play.golang.org/p/ppipUqX9eSF
编辑:H/T 到@perreal 以获得单行建议!
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句