Class: JSON5::NumberValue

Inherits:
Object
  • Object
show all
Defined in:
lib/json5/number_value.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(raw, kind: nil) ⇒ NumberValue

Returns a new instance of NumberValue.



7
8
9
10
11
# File 'lib/json5/number_value.rb', line 7

def initialize(raw, kind: nil)
  @raw = raw.to_s.freeze
  @kind = (kind || classify(@raw)).to_sym
  freeze
end

Instance Attribute Details

#kindObject (readonly)

Returns the value of attribute kind.



5
6
7
# File 'lib/json5/number_value.rb', line 5

def kind
  @kind
end

#rawObject (readonly)

Returns the value of attribute raw.



5
6
7
# File 'lib/json5/number_value.rb', line 5

def raw
  @raw
end

Instance Method Details

#to_fObject



30
31
32
33
34
# File 'lib/json5/number_value.rb', line 30

def to_f
  return hex_to_f if kind == :hex

  to_native.to_f
end

#to_nativeObject



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/json5/number_value.rb', line 13

def to_native
  case kind
  when :infinity
    raw.start_with?("-") ? -Float::INFINITY : Float::INFINITY
  when :nan
    Float::NAN
  when :hex
    sign = raw.start_with?("-") ? -1 : 1
    sign * Integer(raw.delete_prefix("+").delete_prefix("-"), 16)
  when :integer
    return -0.0 if raw == "-0"
    Integer(raw, 10)
  else
    decimal_to_float
  end
end