Skip to content

Instantly share code, notes, and snippets.

@descovi
Last active January 25, 2021 18:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save descovi/5056ab3f433db61c7c19d040c4c03921 to your computer and use it in GitHub Desktop.
Save descovi/5056ab3f433db61c7c19d040c4c03921 to your computer and use it in GitHub Desktop.
Ruby Wei to eth converter
# Example of usage:
# result = WeiConverter.new(1890000000000000000).call
# Result contains 1.89
class WeiConverter
UNITS = {
wei: 1,
kwei: 1000,
ada: 1000,
femtoether: 1000,
mwei: 1000000,
babbage: 1000000,
picoether: 1000000,
gwei: 1000000000,
shannon: 1000000000,
nanoether: 1000000000,
nano: 1000000000,
szabo: 1000000000000,
microether: 1000000000000,
micro: 1000000000000,
finney: 1000000000000000,
milliether: 1000000000000000,
milli: 1000000000000000,
ether: 1000000000000000000,
eth: 1000000000000000000,
kether: 1000000000000000000000,
grand: 1000000000000000000000,
einstein: 1000000000000000000000,
mether: 1000000000000000000000000,
gether: 1000000000000000000000000000,
tether: 1000000000000000000000000000000
}
def initialize(amount)
@amount = amount
end
def call(unit: "ether")
return nil if @amount.nil?
unit = UNITS[unit.to_sym]
(BigDecimal.new(@amount, 16) / BigDecimal.new(unit, 16)).to_s rescue nil
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment