英文:
Converting big.Float to string with variable precision Go
问题
我已经编写了一个方法,可以将big.Float转换为字符串,并根据给定的精度四舍五入。它接受所需的精度和数量作为参数。然而,现在我需要将这个方法改为动态的,而不是使用switch语句,手动编写会变得非常混乱。所以,有人知道如何实现这个吗?
我已经查看了strconv.FormatFloat(),我认为它可以实现我想要的行为,但它只适用于float64,而不是big.Float。
英文:
I have made a method that converts a big.Float to a string while rounding it based on a given precision, it takes in the wanted precision and the amount, however I now need to make this method dynamic instead of in a switch, and writing it by hand gets extremely messy. So does anyone have a way of doing this?
func (a *AssetServiceImpl) AsStringFromFloat(precision int, amount *big.Float) (string, error) {
switch precision {
case 8:
return fmt.Sprintf(strings.TrimRight(strings.TrimRight(fmt.Sprintf("%.8f", amount), "0"), ".")), nil
case 12:
return fmt.Sprintf(strings.TrimRight(strings.TrimRight(fmt.Sprintf("%.12f", amount), "0"), ".")), nil
case 18:
return fmt.Sprintf(strings.TrimRight(strings.TrimRight(fmt.Sprintf("%.18f", amount), "0"), ".")), nil
}
return "", errors.NewValidationErrors(errors.NewError("Invalid Invalid Asset Precision", errors.InvalidAssetPrecision))
}
I have looked at strconv.FormatFloat(), and I think it can have the behaviour I want, but that is only for float64 and not big.float.
答案1
得分: 1
你可以将格式字符串设为动态的:
func AsStringFromFloat(precision int, amount *big.Float) (string, error) {
fmtString := fmt.Sprintf("%%.%df", precision)
return fmt.Sprintf(strings.TrimRight(strings.TrimRight(fmt.Sprintf(fmtString, amount), "0"), ".")), nil
}
链接:https://go.dev/play/p/L1DOekvlwA6
英文:
You could always just make your format string dynamic:
func AsStringFromFloat(precision int, amount *big.Float) (string, error) {
fmtString := fmt.Sprintf("%%.%df", precision)
return fmt.Sprintf(strings.TrimRight(strings.TrimRight(fmt.Sprintf(fmtString, amount), "0"), ".")), nil
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论