lib/zold/amount.rb in zold-0.8 vs lib/zold/amount.rb in zold-0.9
- old
+ new
@@ -25,30 +25,38 @@
# Copyright:: Copyright (c) 2018 Yegor Bugayenko
# License:: MIT
module Zold
# Amount
class Amount
+ # How many zents are in one ZLD: 2^FRACTION
+ FRACTION = 32
+
+ # Maximum amount of zents
+ MAX = 2**63
+
def initialize(coins: nil, zld: nil)
if !coins.nil?
raise "Integer is required, while #{coins.class} provided: #{coins}" unless coins.is_a?(Integer)
@coins = coins
elsif !zld.nil?
raise "Float is required, while #{zld.class} provided: #{zld}" unless zld.is_a?(Float)
- @coins = (zld * 2**24).to_i
+ @coins = (zld * 2**Amount::FRACTION).to_i
else
raise 'You can\'t specify both coints and zld'
end
+ raise "The amount is too big: #{@coins}" if @coins > Amount::MAX
+ raise "The amount is too small: #{@coins}" if @coins < -Amount::MAX
end
ZERO = Amount.new(coins: 0)
def to_i
@coins
end
def to_zld
- format('%0.2f', @coins.to_f / 2**24)
+ format('%0.2f', @coins.to_f / 2**Amount::FRACTION)
end
def to_s
text = "#{to_zld}ZLD"
if negative?
@@ -96,10 +104,10 @@
@coins < 0
end
def *(other)
c = (@coins * other).to_i
- raise "Overflow, can't multiply #{@coins} by #{m}" if c > 2**63
+ raise "Overflow, can't multiply #{@coins} by #{m}" if c > Amount::MAX
Amount.new(coins: c)
end
end
end