# Class: Hippo::Numbers::PercNum

Inherits:
Object
• Object
show all
Defined in:
lib/hippo/numbers.rb

## Overview

### PercNum

A “percnum” is a Stockor invention *(or abomination, depending on your POV)*. It's a string that contains a number and an optional percent sign. If the percent sign is present, the number is treated as a percentage. If desired the user may also input negative numbers which will invert the sense of the method.

It's intended to be a user-friendly method to provide one input box for “discount” or “surcharge”, and allow the user to input either a flat amount such as 4.50, or a percentage like 20%

## Instance Method Summary collapse

• Adds the PercNum to the specified amount.

• Subtracts the PercNum to the specified amount.

• constructor

A new instance of PercNum.

• Is the PercNum percentage based or absolute.

• If PercNum was initialized with a blank string.

## Constructor Details

### #initialize(perc_or_num) ⇒ PercNum

Returns a new instance of PercNum.

Parameters:

• perc_or_num (BigDecimal, String, Integer)

any value that BigDecimal will accept

 ``` 32 33 34 35 36 37 38``` ```# File 'lib/hippo/numbers.rb', line 32 def initialize( perc_or_num ) @is_perc = !! perc_or_num.to_s.match( /\%\s*\$/ ) @right_side = BigDecimal.new( perc_or_num.gsub(/[^0-9\.\-]/, ''), 5 ) if is_percentage? @right_side *= 0.01 end end```

## Instance Method Details

### #credit_to(amount) ⇒ BigDecimal

Adds the PercNum to the specified amount.

Examples:

``````PercNum.new( '23.42' ).credit_to(  33 ).to_s  #=> '56.42'
PercNum.new( '25%'   ).credit_to( 100 ).to_s  #=> '125.0'``````

Parameters:

• amount (BigDecimal)

the amount that should be added to the PercNum

Returns:

• (BigDecimal)

The result of either adding (non percent) or multiplying by (percent) the amount

 ``` 46 47 48``` ```# File 'lib/hippo/numbers.rb', line 46 def credit_to( amount ) is_percentage? ? ( 1 + @right_side ) * amount : amount += @right_side end```

### #debit_from(amount) ⇒ BigDecimal

Subtracts the PercNum to the specified amount.

Examples:

``````PercNum.new( '23.42' ).debit_from( 42.42 ).to_s  #=> '19.00'
PercNum.new( '25%'   ).debit_from( 100   ).to_s  #=> '75.0'``````

Parameters:

• amount (BigDecimal)

the amount that should be added to the PercNum

Returns:

• (BigDecimal)

The result of either adding (non percent) or multiplying by (percent) the amount

 ``` 56 57 58``` ```# File 'lib/hippo/numbers.rb', line 56 def debit_from( amount ) is_percentage? ? ( 1 - @right_side ) * amount : amount -= @right_side end```

### #is_percentage? ⇒ Boolean

Is the PercNum percentage based or absolute

Returns:

• (Boolean)
 ``` 66 67 68``` ```# File 'lib/hippo/numbers.rb', line 66 def is_percentage? @is_perc end```

### #present? ⇒ Boolean

If PercNum was initialized with a blank string

Returns:

• (Boolean)
 ``` 61 62 63``` ```# File 'lib/hippo/numbers.rb', line 61 def present? ! @right_side.zero? end```