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.
CodePudding user response:
You could always just make your format string dynamic:
func AsStringFromFloat(precision int, amount *big.Float) (string, error) {
fmtString := fmt.Sprintf("%%.