Last active
July 4, 2018 07:38
-
-
Save euforic/7ec6346fa0bcb89db8b52d186d65603c to your computer and use it in GitHub Desktop.
Ethereum Unit Converter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package ethutil | |
import ( | |
"fmt" | |
"math" | |
"math/big" | |
"strings" | |
"github.com/shopspring/decimal" | |
) | |
type unit int | |
const ( | |
Wei unit = 0 | |
Kwei unit = 3 | |
Ada | |
Femtoether | |
Mwei unit = 6 | |
Babbage | |
Picoether | |
Gwei unit = 9 | |
Shannon | |
Nanoether | |
Nano | |
Microether unit = 12 | |
Micro | |
Szabo | |
Milliether unit = 15 | |
Milli | |
Finney | |
Ether unit = 18 | |
Kether unit = 21 | |
Grand | |
Einstein | |
Mether unit = 24 | |
Gether unit = 27 | |
Tether unit = 30 | |
) | |
func (u unit) String() string { | |
v, ok := unitName[u] | |
if !ok { | |
return "" | |
} | |
return v | |
} | |
var unitName = map[unit]string{ | |
Wei: "wei", | |
Kwei: "kwei", | |
Mwei: "mwei", | |
Gwei: "gwei", | |
Szabo: "szabo", | |
Finney: "finney", | |
Ether: "ether", | |
} | |
func EthToWei(eth string) string { | |
return Convert(eth, Ether, Wei).FloatString(0) | |
} | |
func WeiToEth(wei string) string { | |
eth := Convert(wei, Wei, Ether).FloatString(18) | |
return strings.TrimRight(eth, "0") | |
} | |
func Convert(w string, from unit, to unit) *big.Rat { | |
v, ok := new(big.Rat).SetString(w) | |
if !ok { | |
return nil | |
} | |
fromUnit := new(big.Int).SetInt64(int64(math.Pow10(int(from)))) | |
toUnit := new(big.Int).SetInt64(int64(math.Pow10(int(to)))) | |
return v.Mul(v, new(big.Rat).SetFrac(fromUnit, toUnit)) | |
} | |
func Convert2(w string, from unit, to unit) string { | |
v, _ := decimal.NewFromString(w) | |
fromUnit := decimal.NewFromFloat(10).Pow(decimal.NewFromFloat(float64(from))) | |
toUnit := decimal.NewFromFloat(10).Pow(decimal.NewFromFloat(float64(to))) | |
fmt.Println(fromUnit.String(), toUnit.String()) | |
res := v.Mul(fromUnit).Div(toUnit).String() | |
return res | |
} | |
func Convert3(w string, from unit, to unit) string { | |
v, ok := new(big.Float).SetString(w) | |
if !ok { | |
return "" | |
} | |
fromUnit := new(big.Float).SetFloat64(math.Pow10(int(from))) | |
toUnit := new(big.Float).SetFloat64(math.Pow10(int(to))) | |
return v.Mul(v, fromUnit).Quo(v, toUnit).Text('f', 0) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment