2023-08-07 09:28:49 +01:00
|
|
|
package strconv
|
|
|
|
|
|
|
|
import (
|
|
|
|
"math"
|
|
|
|
)
|
|
|
|
|
2023-10-30 10:06:51 +00:00
|
|
|
// ParseDecimal parses number of the format 1.2
|
2023-08-07 09:28:49 +01:00
|
|
|
func ParseDecimal(b []byte) (float64, int) {
|
2023-10-30 10:06:51 +00:00
|
|
|
// float64 has up to 17 significant decimal digits and an exponent in [-1022,1023]
|
2023-08-07 09:28:49 +01:00
|
|
|
i := 0
|
2023-10-30 10:06:51 +00:00
|
|
|
//sign := 1.0
|
|
|
|
//if 0 < len(b) && b[0] == '-' {
|
|
|
|
// sign = -1.0
|
|
|
|
// i++
|
|
|
|
//}
|
|
|
|
|
|
|
|
start := -1
|
2023-08-07 09:28:49 +01:00
|
|
|
dot := -1
|
|
|
|
n := uint64(0)
|
|
|
|
for ; i < len(b); i++ {
|
2023-10-30 10:06:51 +00:00
|
|
|
// parse up to 18 significant digits (with dot will be 17) ignoring zeros before/after
|
2023-08-07 09:28:49 +01:00
|
|
|
c := b[i]
|
|
|
|
if '0' <= c && c <= '9' {
|
2023-10-30 10:06:51 +00:00
|
|
|
if start == -1 {
|
|
|
|
if '1' <= c && c <= '9' {
|
|
|
|
n = uint64(c - '0')
|
|
|
|
start = i
|
2023-08-07 09:28:49 +01:00
|
|
|
}
|
2023-10-30 10:06:51 +00:00
|
|
|
} else if i-start < 18 {
|
|
|
|
n *= 10
|
|
|
|
n += uint64(c - '0')
|
|
|
|
}
|
|
|
|
} else if c == '.' {
|
|
|
|
if dot != -1 {
|
|
|
|
break
|
2023-08-07 09:28:49 +01:00
|
|
|
}
|
|
|
|
dot = i
|
|
|
|
} else {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
2023-10-30 10:06:51 +00:00
|
|
|
if i == 1 && dot == 0 {
|
|
|
|
return 0.0, 0 // only dot
|
|
|
|
} else if start == -1 {
|
|
|
|
return 0.0, i // only zeros and dot
|
|
|
|
} else if dot == -1 {
|
|
|
|
dot = i
|
2023-08-07 09:28:49 +01:00
|
|
|
}
|
|
|
|
|
2023-10-30 10:06:51 +00:00
|
|
|
exp := (dot - start) - LenUint(n)
|
|
|
|
if dot < start {
|
|
|
|
exp++
|
|
|
|
}
|
|
|
|
if 1023 < exp {
|
|
|
|
return math.Inf(1), i
|
|
|
|
//if sign == 1.0 {
|
|
|
|
// return math.Inf(1), i
|
|
|
|
//} else {
|
|
|
|
// return math.Inf(-1), i
|
|
|
|
//}
|
|
|
|
} else if exp < -1022 {
|
|
|
|
return 0.0, i
|
2023-08-07 09:28:49 +01:00
|
|
|
}
|
|
|
|
|
2023-10-30 10:06:51 +00:00
|
|
|
f := float64(n) // sign * float64(n)
|
|
|
|
if 0 <= exp && exp < 23 {
|
|
|
|
return f * float64pow10[exp], i
|
|
|
|
} else if 23 < exp && exp < 0 {
|
|
|
|
return f / float64pow10[exp], i
|
2023-08-07 09:28:49 +01:00
|
|
|
}
|
2023-10-30 10:06:51 +00:00
|
|
|
return f * math.Pow10(exp), i
|
2023-08-07 09:28:49 +01:00
|
|
|
}
|