diff --git a/lib/satoshi.rb b/lib/satoshi.rb index 4c76375..7d969da 100644 --- a/lib/satoshi.rb +++ b/lib/satoshi.rb @@ -5,6 +5,7 @@ class Satoshi UNIT_DENOMINATIONS = { btc: 8, mbtc: 5, + bits: 2, satoshi: 0 } @@ -29,6 +30,10 @@ def to_mbtc(as: :number) to_denomination(UNIT_DENOMINATIONS[:mbtc], as: as) end + def to_bits(as: :number) + to_denomination(UNIT_DENOMINATIONS[:bits], as: as) + end + def to_unit(as: :number) to_denomination(UNIT_DENOMINATIONS[@to_unit], as: as) end @@ -37,7 +42,7 @@ def to_i return 0 if @value.nil? @value end - alias :satoshi_value :to_i + alias :satoshi_value :to_i def value=(n) n = 0 if n.nil? @@ -89,7 +94,7 @@ def coerce(other) end private - + def to_denomination(digits_after_delimiter, as: :number) sign = @value < 0 ? -1 : 1 val = @value.abs @@ -101,7 +106,7 @@ def to_denomination(digits_after_delimiter, as: :number) result.reverse! result = result.sub(/\A0*/, '').sub(/0*\Z/, '') # remove zeros on both sides if as == :number - result.to_f*sign + result.to_f*sign else if result == '.' result = '0.0' @@ -114,9 +119,9 @@ def to_denomination(digits_after_delimiter, as: :number) def convert_to_satoshi(n) n = ("%.#{UNIT_DENOMINATIONS[@from_unit]}f" % n) # otherwise we might see a scientific notation - n = n.split('.') + n = n.split('.') n[1] ||= '' # in the case where there's no decimal part - n[1] += "0"*(UNIT_DENOMINATIONS[@from_unit]-n[1].length) if n[1] + n[1] += "0"*(UNIT_DENOMINATIONS[@from_unit]-n[1].length) if n[1] n.join.to_i end diff --git a/spec/satoshi_spec.rb b/spec/satoshi_spec.rb index 2a01df9..abdfacc 100644 --- a/spec/satoshi_spec.rb +++ b/spec/satoshi_spec.rb @@ -14,11 +14,12 @@ expect(Satoshi.new(1.00).to_btc).to eq(1) expect(Satoshi.new(1.08763).to_btc).to eq(1.08763) expect(Satoshi.new(1.08763).to_mbtc).to eq(1087.63) + expect(Satoshi.new(1.08763).to_bits).to eq(1087630.0) expect(Satoshi.new(-1.08763).to_mbtc).to eq(-1087.63) expect(Satoshi.new(0.00000001).to_i).to eq(1) expect(Satoshi.new(0.00000001).to_mbtc).to eq(0.00001) end - + it "converts from various source denominations" do expect(Satoshi.new(1, unit: 'mbtc').to_btc).to eq(0.001) expect(Satoshi.new(1, unit: 'mbtc').to_unit).to eq(1)