Skip to content

Instantly share code, notes, and snippets.

@xlab
Created February 2, 2017 20:17
Show Gist options
  • Save xlab/10f16ceb0f51ae6ea771cb412bc85a58 to your computer and use it in GitHub Desktop.
Save xlab/10f16ceb0f51ae6ea771cb412bc85a58 to your computer and use it in GitHub Desktop.
JSON Number parsing for Go, ported from C version in cJSON
package parseFloat
import "math"
func Parse(num []byte) (n float64) {
var (
sign float64 = 1
scale int
subscale int
signsubscale int = 1
)
func() {
var i int
// has sign?
if num[i] == '-' {
sign = -1
i++
if i >= len(num) {
return
}
}
// is zero
if num[i] == '0' {
i++
if i >= len(num) {
return
}
}
// number?
if num[i] >= '1' && num[i] <= '9' {
for num[i] >= '0' && num[i] <= '9' {
n = n*10 + float64(num[i]-'0')
i++
if i >= len(num) {
return
}
}
}
// fractional part?
if num[i] == '.' && (num[i+1] >= '0' && num[i+1] <= '9') {
i++
if i >= len(num) {
return
}
for num[i] >= '0' && num[i] <= '9' {
n = n*10 + float64(num[i]-'0')
i++
if i >= len(num) {
return
}
scale--
}
}
// exponent?
if num[i] == 'e' || num[i] == 'E' {
i++
if i >= len(num) {
return
}
// with sign?
if num[i] == '+' {
i++
if i >= len(num) {
return
}
} else if num[i] == '-' {
signsubscale = -1
i++
if i >= len(num) {
return
}
}
// number?
for num[i] >= '0' && num[i] <= '9' {
subscale = subscale*10 + int(num[i]-'0')
i++
if i >= len(num) {
return
}
}
}
}()
// number = +/- number.fraction * 10^+/- exponent
n = sign * n * math.Pow10(scale+subscale*signsubscale)
return
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment