github.com/aergoio/aergo@v1.3.1/cmd/aergocli/util/unit.go (about)

     1  package util
     2  
     3  import (
     4  	"fmt"
     5  	"math/big"
     6  	"strconv"
     7  	"strings"
     8  )
     9  
    10  //var unit map[string]*big.Int
    11  var units map[string]int
    12  var unitlist []string
    13  
    14  func init() {
    15  	units = map[string]int{}
    16  	units["aergo"] = 18
    17  	units["gaer"] = 9
    18  	units["aer"] = 0
    19  	unitlist = []string{"aergo", "gaer", "aer"}
    20  }
    21  
    22  func ParseUnit(s string) (*big.Int, error) {
    23  	result, ok := new(big.Int).SetString(strings.TrimSpace(s), 10)
    24  	if !ok {
    25  		lower := strings.ToLower(s)
    26  		for _, v := range unitlist {
    27  			if strings.Contains(lower, v) {
    28  				number := strings.TrimSpace(strings.TrimSuffix(lower, v))
    29  				numbers := strings.Split(number, ".")
    30  				var nstr string
    31  				var pos int
    32  				switch len(numbers) {
    33  				case 1:
    34  					nstr = numbers[0]
    35  					pos = 0
    36  				case 2:
    37  					if len(numbers[1]) > units[v] {
    38  						return big.NewInt(0), fmt.Errorf("too small unit %s", s)
    39  					}
    40  					nstr = numbers[0] + numbers[1]
    41  					pos = len(numbers[1])
    42  				default:
    43  					continue
    44  				}
    45  				for i := pos; i < units[v]; i++ {
    46  					nstr += "0"
    47  				}
    48  				n, ok := new(big.Int).SetString(nstr, 10)
    49  				if !ok {
    50  					continue
    51  				} else {
    52  					return n, nil
    53  				}
    54  			}
    55  		}
    56  		return big.NewInt(0), fmt.Errorf("could not parse %s", s)
    57  	}
    58  	return result, nil
    59  }
    60  
    61  func ConvertUnit(n *big.Int, unit string) (string, error) {
    62  	unit = strings.ToLower(unit)
    63  	nstr := n.String()
    64  
    65  	if len(nstr) > units[unit] {
    66  		dotpos := len(nstr) - units[unit]
    67  		nstr = nstr[0:dotpos] + "." + nstr[dotpos:]
    68  		return strings.TrimRight(strings.TrimRight(nstr, "0"), ".") + " " + unit, nil
    69  	}
    70  	result := strings.TrimRight(fmt.Sprintf(".%0"+strconv.Itoa(units[unit])+"d", n), ".0")
    71  	result = "0" + result + " " + unit
    72  	return result, nil
    73  }