From 280c382a3d1b4fb035891df51d79836d6c59ff6d Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Thu, 26 Jun 2025 12:19:13 +0300 Subject: [PATCH] add a helper function 'TruncateDecimalString' to format amounts to specified decimal places --- store/tokens.go | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/store/tokens.go b/store/tokens.go index ce8dd7d..49ac175 100644 --- a/store/tokens.go +++ b/store/tokens.go @@ -3,6 +3,7 @@ package store import ( "context" "errors" + "fmt" "math/big" "reflect" "strconv" @@ -20,6 +21,27 @@ type TransactionData struct { ActiveAddress string } +// TruncateDecimalString safely truncates the input amount to the specified decimal places +func TruncateDecimalString(input string, decimalPlaces int) (string, error) { + num, ok := new(big.Float).SetString(input) + if !ok { + return "", fmt.Errorf("invalid input") + } + + // Multiply by 10^decimalPlaces + scale := new(big.Float).SetInt(new(big.Int).Exp(big.NewInt(10), big.NewInt(int64(decimalPlaces)), nil)) + scaled := new(big.Float).Mul(num, scale) + + // Truncate by converting to int (chops off decimals) + intPart, _ := scaled.Int(nil) + + // Divide back to get truncated float + truncated := new(big.Float).Quo(new(big.Float).SetInt(intPart), scale) + + // Format with fixed decimals + return truncated.Text('f', decimalPlaces), nil +} + func ParseAndScaleAmount(storedAmount, activeDecimal string) (string, error) { // Parse token decimal tokenDecimal, err := strconv.Atoi(activeDecimal)