-
Notifications
You must be signed in to change notification settings - Fork 17
/
floating-point.go
47 lines (39 loc) · 892 Bytes
/
floating-point.go
1
2
3
4
5
6
7
8
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
35
36
37
38
39
40
41
42
43
44
45
46
47
package main
import (
"encoding/json"
"fmt"
"github.com/alexflint/go-restructure"
)
var floatRegexp = restructure.MustCompile(Float{}, restructure.Options{})
// Matches "123", "1.23", "1.23e-4", "-12.3E+5", ".123"
type Float struct {
Sign *Sign `?`
Whole string `[0-9]*`
Period struct{} `\.?`
Frac string `[0-9]+`
Exponent *Exponent `?`
}
// Matches "+" or "-"
type Sign struct {
Ch string `[+-]`
}
// Matches "e+4", "E6", "e-03"
type Exponent struct {
_ struct{} `[eE]`
Sign *Sign `?`
Num string `[0-9]+`
}
func prettyPrint(x interface{}) string {
buf, err := json.MarshalIndent(x, "", " ")
if err != nil {
return err.Error()
}
return string(buf)
}
func main() {
var f Float
for _, str := range []string{"1.23", "1.23e+45", ".123", "12e3"} {
floatRegexp.Find(&f, str)
fmt.Printf("\"%s\" -> %s\n\n", str, prettyPrint(f))
}
}