add a helper function 'TruncateDecimalString' to format amounts to specified decimal places
This commit is contained in:
parent
88926480dc
commit
280c382a3d
@ -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)
|
||||
|
Loading…
Reference in New Issue
Block a user