I have a float64 I converted into a string: 30.060671
I'm trying to trim/remove/chomp everything after 30
Some of the things I've tried:
fmt.Println(strings.TrimRight("30.060671", ".([0-9])"))
fmt.Println(strings.TrimRight("30.060671", "."))
fmt.Println(strings.TrimSuffix("30.060671", "."))
One way to do it would be to use strings.Split on the period:
parts := strings.Split("30.060671", ".")
fmt.Println(parts[0])
Another option is to convert to an int first and then to a string:
a := 30.060671
b := int(a)
fmt.Println(b)
As per @pайтфолд suggested in comment, you should have rounded the float before converting to string.
Anyway, here is my attempt using strings.Index to trim the remaining from .
:
func trimStringFromDot(s string) string {
if idx := strings.Index(s, "."); idx != -1 {
return s[:idx]
}
return s
}
Playground
Also, to answer why TrimRight and TrimSuffix not working as expected is because .
is not a trailing string/unicode:
TrimRight returns a slice of the string s, with all trailing Unicode code points contained in cutset removed.
TrimSuffix returns s without the provided trailing suffix string. If s doesn't end with suffix, s is returned unchanged.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With