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
}
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.
Here is how to get either side of a delimiter.
string := "Symver.0.1.0"
delimiter := "."
leftOfDelimiter := strings.Split(string, delimiter)[0]
rightOfDelimiter := strings.Join(strings.Split(string, delimiter)[1:], delimiter)
fmt.Println("Left of Delimiter: ", leftOfDelimiter)
fmt.Println("Right of Delimiter: ", rightOfDelimiter)
//Left of Delimiter: Symver
//Right of Delimiter: 0.1.0
fmt.Println(fmt.Sprintf("%.0f", 30.060671))
That oughtta do it easy. (BTW: Just to add, one of the commenters originally stated or alluded to a similar solution). However must you only use string, this should do -
fmt.Println(fmt.Sprintf("%.0f", 30.060671))
value := "30.060671"
f := func(c rune) bool {
return c == ',' || c == ':' || c == '.'
}
fields := strings.FieldsFunc(value, f)[0]
fmt.Printf("%v", fields)
You have choice of delimiters there. I don't know if this is elegant but hey.