Class: GOBL::Num::Percentage

Inherits:
Amount show all
Defined in:
lib/gobl/num/percentage.rb

Overview

Similar to Amount, but specialized in representing percentages

Instance Attribute Summary

Attributes inherited from Amount

#exp, #value

Instance Method Summary collapse

Methods inherited from Amount

#==, #add, #as_json, #as_s, #compare, #divide, #initialize, #invert, #multiply, #rescale, rescale_pair, #split, #subtract, #zero?

Methods inherited from Struct

#as_json, from_data, from_json!, #to_json

Constructor Details

This class inherits a constructor from GOBL::Num::Amount

Instance Method Details

#factorGOBL::Num::Amount

Returns the percentage amount as a factor, adding 1 to the rate

Returns:



59
60
61
# File 'lib/gobl/num/percentage.rb', line 59

def factor
  Amount.new(value: value, exp: exp).add(Factor1)
end

#from(a) ⇒ GOBL::Num::Amount

Calculates what “percent from” the given amount would result assuming the rate has already been applied. Put otherwise, for a given amount that was increased by the current percentage, this method returns the amount of that increment.

Examples:

original_amount = GOBL::Num::Amount.new("200")
percentage = GOBL::Num::Percentage.new("25%")
increment = percentage.of(original_amount) #=> 50

increased_amount = original_amount.add(increment) #=> 250
percentage.from(increased_amount) #=> 50

Parameters:

Returns:



51
52
53
54
# File 'lib/gobl/num/percentage.rb', line 51

def from(a)
  x = a.divide(factor)
  a.subtract(x)
end

#of(a) ⇒ GOBL::Num::Amount

Calculates the “percent of” a given amount

Parameters:

Returns:



32
33
34
# File 'lib/gobl/num/percentage.rb', line 32

def of(a)
  a.multiply(self)
end

#to_sString

Returns a string representation of the percentage with the percentage symbol

Returns:

  • (String)

    the string representing the percentage



13
14
15
# File 'lib/gobl/num/percentage.rb', line 13

def to_s
  "#{to_s_without_symbol}%"
end

#to_s_without_symbolString

Returns a string representation of the percentage with_out the percentage symbol

Returns:

  • (String)

    the string representing the percentage



20
21
22
23
24
25
# File 'lib/gobl/num/percentage.rb', line 20

def to_s_without_symbol
  e = exp - 2
  e = 0 if e.negative?
  p = multiply(Factor100).rescale(e)
  p.as_s
end