Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TrimRight everything after delimiter in golang

Tags:

go

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", "."))
like image 231
Tim Ski Avatar asked Apr 11 '15 17:04

Tim Ski


2 Answers

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)
like image 130
IamNaN Avatar answered Sep 19 '22 15:09

IamNaN


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.

like image 24
Anzel Avatar answered Sep 19 '22 15:09

Anzel