package biginthelper import ( "bytes" "fmt" "math/big" "strings" ) // BigIntString BigIntString func BigIntString(balance *big.Int, decimals int64) string { amount := BigIntFloat(balance, decimals) deci := fmt.Sprintf("%%0.%vf", decimals) return clean(fmt.Sprintf(deci, amount)) } // BigIntFloat BigIntFloat func BigIntFloat(balance *big.Int, decimals int64) *big.Float { if balance.Sign() == 0 { return big.NewFloat(0) } bal := new(big.Float) bal.SetInt(balance) pow := bigPow(10, decimals) p := big.NewFloat(0) p.SetInt(pow) bal.Quo(bal, p) return bal } func bigPow(a, b int64) *big.Int { r := big.NewInt(a) return r.Exp(r, big.NewInt(b), nil) } func clean(newNum string) string { stringBytes := bytes.TrimRight([]byte(newNum), "0") newNum = string(stringBytes) if stringBytes[len(stringBytes)-1] == 46 { newNum += "0" } if stringBytes[0] == 46 { newNum = "0" + newNum } return newNum } // GetActualHex 获取真实的十六进制.. func GetActualHex(h string) string { h = strings.TrimLeft(h, "0") var hex string if strings.Index(h, "0x") == 0 { hex = h[2:] } else { hex = h } if len(h)%2 != 0 { hex = "0" + hex } return "0x" + hex } // HexToBig HexToBig func HexToBig(h string) *big.Int { i := big.NewInt(0) h = strings.Replace(h, "0x", "", -1) if h == "" { return i } if _, ok := i.SetString(h, 16); !ok { return nil } return i } // ConvertNumToFloat ConvertNumToFloat func ConvertNumToFloat(num int64) float64 { switch num { case 1: return 10.0 case 2: return 100.0 case 3: return 1000.0 case 4: return 10000.0 case 5: return 100000.0 case 6: return 1000000.0 case 7: return 10000000.0 case 8: return 100000000.0 case 9: return 1000000000.0 case 10: return 10000000000.0 case 11: return 100000000000.0 case 12: return 1000000000000.0 case 13: return 10000000000000.0 case 14: return 100000000000000.0 case 15: return 1000000000000000.0 case 16: return 10000000000000000.0 case 17: return 100000000000000000.0 case 18: return 1000000000000000000.0 default: return 0.0 } }