A Ruby gem to manipulate Bitcoin money without loss of precision.
In simple operations like 0.3 - 0.1
(using Float
data types) the result may be a bit strange:
difference = 0.3 - 0.1
puts difference
# 0.19999999999999998
Using the Satoshis gem you get:
difference = Satoshis.new("0.3") - Satoshis.new("0.1")
puts difference.to_s
# "0.2"
And you can do some conversions of bitcoin values:
satoshis = 420000
amount = Satoshis.new(satoshis)
puts amount.to_s
# "0.0042"
# String
puts amount.to_d
# 0.42e-2
# BigDecimal
puts amount.to_i
# 420000
# Integer (satoshis)
Add this line to your application's Gemfile:
gem "satoshis"
And then execute:
bundle install
Or install it yourself as:
gem install satoshis
Use the class CoinDecimal
passing the argument precision
:
satoshis = 42
amount = CoinDecimal.new(satoshis, 10)
puts amount.to_s
# "0.0000000042"
# String