# Class: Unitwise::Number

Inherits:
Object
• Object
show all
Defined in:
lib/unitwise/number.rb

## Class Method Summary collapse

• Coerces a string-like number to a BigDecimal or Integer as appropriate.

• Coerce a numeric to a Rational, but avoid inaccurate conversions by jruby.

• Attempts to coerce a value to the simplest Numeric that fully expresses it's value.

## Class Method Details

### .coefficify(value) ⇒ Integer, BigDecimal

Coerces a string-like number to a BigDecimal or Integer as appropriate

Parameters:

• value

Something that can be represented as a string number

Returns:

• (Integer, BigDecimal)
 ``` 40 41 42 43 44 45 46 47``` ```# File 'lib/unitwise/number.rb', line 40 def self.coefficify(value) d = BigDecimal.new(value.to_s) if (i = d.to_i) == d i else d end end```

### .rationalize(number) ⇒ Object

Coerce a numeric to a Rational, but avoid inaccurate conversions by jruby. More details here: github.com/jruby/jruby/issues/4711.

Parameters:

• number (Numeric)

Returns:

• Rational

 ``` 54 55 56 57 58 59 60``` ```# File 'lib/unitwise/number.rb', line 54 def self.rationalize(number) if number.is_a?(BigDecimal) && RUBY_PLATFORM == 'java' number.to_s.to_r else number.to_r end end```

### .simplify(value) ⇒ Integer, ...

Attempts to coerce a value to the simplest Numeric that fully expresses it's value. For instance a value of 1.0 would return 1, a value of #<BigDecimal:7f9558d559b8,'0.45E1',18(18)> would return 4.5.

Parameters:

• value (Integer, Float, Rational, String, BigDecimal)

Returns:

• (Integer, Float, Rational, BigDecimal)
 ``` 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34``` ```# File 'lib/unitwise/number.rb', line 9 def self.simplify(value) case value when Integer value when Float (i = value.to_i) == value ? i : value when Rational if (i = value.to_i) == value i elsif (f = value.to_f) && f.to_r == value f else value end else # String, BigDecimal, Other s = value.is_a?(String) ? value : value.to_s d = value.is_a?(BigDecimal) ? value : BigDecimal(s) if (i = d.to_i) == d i elsif (f = d.to_f) == d f else d end end end```