将big.Float转换为具有可变精度的字符串,使用Go语言。

huangapple go评论83阅读模式
英文:

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
}

https://go.dev/play/p/L1DOekvlwA6

huangapple
  • 本文由 发表于 2022年10月22日 01:24:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/74157198.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定