fix gstr.IsNumeric

This commit is contained in:
John Guo 2022-01-17 19:42:21 +08:00
parent 56f88f759a
commit 220ed74ad1
2 changed files with 9 additions and 1 deletions

View File

@ -50,7 +50,10 @@ func IsLetter(b byte) bool {
// IsNumeric checks whether the given string s is numeric. // IsNumeric checks whether the given string s is numeric.
// Note that float string like "123.456" is also numeric. // Note that float string like "123.456" is also numeric.
func IsNumeric(s string) bool { func IsNumeric(s string) bool {
length := len(s) var (
dotCount = 0
length = len(s)
)
if length == 0 { if length == 0 {
return false return false
} }
@ -59,6 +62,7 @@ func IsNumeric(s string) bool {
continue continue
} }
if s[i] == '.' { if s[i] == '.' {
dotCount++
if i > 0 && i < len(s)-1 { if i > 0 && i < len(s)-1 {
continue continue
} else { } else {
@ -69,6 +73,9 @@ func IsNumeric(s string) bool {
return false return false
} }
} }
if dotCount > 1 {
return false
}
return true return true
} }

View File

@ -80,6 +80,7 @@ func Test_IsNumeric(t *testing.T) {
t.Assert(gstr.IsNumeric("1a我"), false) t.Assert(gstr.IsNumeric("1a我"), false)
t.Assert(gstr.IsNumeric("0123"), true) t.Assert(gstr.IsNumeric("0123"), true)
t.Assert(gstr.IsNumeric("我是中国人"), false) t.Assert(gstr.IsNumeric("我是中国人"), false)
t.Assert(gstr.IsNumeric("1.2.3.4"), false)
}) })
} }