Skip to content
dismaldenizen edited this page Oct 17, 2010 · 8 revisions

The following grammar parses various representations of integers and floating point numbers.

grammar Number
  rule number
    float / integer
  end

  rule float
    (
      # Scientific notation (eg 5e7, 2.2E-4)
      [+-]? ([0-9]* '.')? [0-9]+ [eE] [+-]? [0-9]+
      /
      # Standard float (eg -43.21, .05)
      [+-]? [0-9]* '.' [0-9]+
    ) {
      def eval
        Float(text_value)
      end
    }
  end

  rule integer
    (
      # Binary (eg 0b101, -0B0010)
      [+-]? '0' [bB] [01]+
      /
      # Hex (eg 0xfff, +0XA30)
      [+-]? '0' [xX] [0-9a-fA-F]+
      /
      # Decimal (eg 27, -421)
      [+-]? [0-9]+
    ) {
      def eval
        Integer(text_value)
      end
    }
  end
end

Sample results:

NumberParser.new.parse("43e4").eval       #=> 430000.0
NumberParser.new.parse("-0b10010").eval   #=> -18
NumberParser.new.parse("-.05").eval       #=> -0.05
Clone this wiki locally