Class: Istox::FMath

Inherits:
Object
  • Object
show all
Defined in:
lib/istox/helpers/f_math.rb

Class Method Summary collapse

Class Method Details

.add(x, y) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
# File 'lib/istox/helpers/f_math.rb', line 5

def add(x, y)
  BigDecimal.mode(BigDecimal::ROUND_MODE, :down)

  x = 0 if x.blank?
  y = 0 if y.blank?

  x = ::BigDecimal.new(x.to_s)
  y = ::BigDecimal.new(y.to_s)

  x.add(y, 100).truncate(18).to_s
end

.div(x, y) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/istox/helpers/f_math.rb', line 41

def div(x, y)
  BigDecimal.mode(BigDecimal::ROUND_MODE, :down)

  x = 0 if x.blank?
  y = 0 if y.blank?

  # x = to_fixed(x)
  # y = to_fixed(y)

  (::BigDecimal.new(x.to_s) / ::BigDecimal.new(y.to_s)).truncate(18).to_s

  # return ::BigDecimal.new('1').to_s if x == y

  # fixed1 = ::BigDecimal.new('1e18')

  # return from_fixed(x.div(y, 100).mult(fixed1, 100)).to_s if x.div(y, 100).modulo(BigDecimal.new(10)).zero? && x.modulo(y).zero?

  # r_y = fixed1.mult(fixed1, 100).truncate(0).div(y, 100).truncate(0)

  # result = from_fixed(x.mult(r_y, 100).truncate(0).div(fixed1, 100).truncate(0))

  # result.truncate(18).to_s
end

.mul(x, y) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
# File 'lib/istox/helpers/f_math.rb', line 29

def mul(x, y)
  BigDecimal.mode(BigDecimal::ROUND_MODE, :down)

  x = 0 if x.blank?
  y = 0 if y.blank?

  x = ::BigDecimal.new(x.to_s)
  y = ::BigDecimal.new(y.to_s)

  x.mult(y, 100).truncate(18).to_s
end

.round(x, digits, rounding_mechanism: 'down') ⇒ Object

rounding mechanism can be ‘down’, ‘up’, or ‘natural’ by default will be :down



85
86
87
88
89
90
# File 'lib/istox/helpers/f_math.rb', line 85

def round(x, digits, rounding_mechanism: 'down')
  return round_up(x, digits) if rounding_mechanism == 'up'
  return round_half_up(x, digits) if rounding_mechanism == 'natural'

  round_down(x, digits)
end

.round_down(x, digits) ⇒ Object



71
72
73
74
75
# File 'lib/istox/helpers/f_math.rb', line 71

def round_down(x, digits)
  BigDecimal.mode(BigDecimal::ROUND_MODE, :down)
  x = 0 if x.blank?
  ::BigDecimal.new(x.to_s).round(digits).to_s
end

.round_half_up(x, digits) ⇒ Object



77
78
79
80
81
# File 'lib/istox/helpers/f_math.rb', line 77

def round_half_up(x, digits)
  BigDecimal.mode(BigDecimal::ROUND_MODE, :half_up)
  x = 0 if x.blank?
  ::BigDecimal.new(x.to_s).round(digits).to_s
end

.round_up(x, digits) ⇒ Object



65
66
67
68
69
# File 'lib/istox/helpers/f_math.rb', line 65

def round_up(x, digits)
  BigDecimal.mode(BigDecimal::ROUND_MODE, :up)
  x = 0 if x.blank?
  ::BigDecimal.new(x.to_s).round(digits).to_s
end

.sub(x, y) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
# File 'lib/istox/helpers/f_math.rb', line 17

def sub(x, y)
  BigDecimal.mode(BigDecimal::ROUND_MODE, :down)

  x = 0 if x.blank?
  y = 0 if y.blank?

  x = ::BigDecimal.new(x.to_s)
  y = ::BigDecimal.new(y.to_s)

  x.sub(y, 100).truncate(18).to_s
end