Last active
January 6, 2019 21:53
-
-
Save zeddee/6f1c15aef3a35609c425ee4988099dae to your computer and use it in GitHub Desktop.
DO NOT USE. Attempt to convert Eth to Wei. Not 100% accurate.
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
// Attempt to convert Eth to Wei | |
package utils | |
import ( | |
"log" | |
"math" | |
"math/big" | |
) | |
// EthToWei converts eth to wei | |
// Doesn't work. Can't get 100% accuracy | |
func EthToWei(ethAmount *big.Float) *big.Int { | |
log.Printf("Input eth: %18.18f\n", ethAmount) | |
factor := big.NewFloat(math.Pow10(18)) | |
log.Printf("factor: %f", factor) | |
wei := ethAmount.Mul(ethAmount, factor) | |
log.Printf("resulting wei (big.Float64): %18.18f", wei) | |
out, accuracy := wei.Int64() | |
if accuracy != big.Exact { | |
log.Fatalf("could not convert eth %d to wei", ethAmount) | |
return nil | |
} | |
log.Printf("out: %d, accuracy: %v", out, accuracy) | |
return big.NewInt(out) | |
} | |
// Want: 3141592653589793238 | |
// But gets: 3141592653589793280 |
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 utils | |
import ( | |
"math/big" | |
"reflect" | |
"testing" | |
) | |
func TestEthToWei(t *testing.T) { | |
type args struct { | |
ethAmount *big.Float | |
} | |
tests := []struct { | |
name string | |
args args | |
want *big.Int | |
}{ | |
{ | |
name: "Convert 1 eth to 10^18 wei", | |
args: args{ethAmount: big.NewFloat(3.141592653589793238)}, | |
want: big.NewInt(3141592653589793238), | |
}, | |
} | |
for _, tt := range tests { | |
t.Run(tt.name, func(t *testing.T) { | |
if got := EthToWei(tt.args.ethAmount); !reflect.DeepEqual(got, tt.want) { | |
t.Errorf("EthToWei() = %v, want %v", got, tt.want) | |
} | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment