Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 10 additions & 5 deletions lib/satoshi.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ class Satoshi
UNIT_DENOMINATIONS = {
btc: 8,
mbtc: 5,
bits: 2,
satoshi: 0
}

Expand All @@ -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
Expand All @@ -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?
Expand Down Expand Up @@ -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
Expand All @@ -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'
Expand All @@ -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

Expand Down
3 changes: 2 additions & 1 deletion spec/satoshi_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down