简体   繁体   English

将float64转换为结果中不含[]的字符串

[英]float64 to string without [] in result

I'm trying to scan some folders and sort them to find the highest version number. 我正在尝试扫描一些文件夹并对它们进行排序,以找到最高的版本号。 {"10.1","9.6","7.2"} and then build a path. {“ 10.1”,“ 9.6”,“ 7.2”},然后建立路径。 However, What I get has [] brackets in the path and I need to get rid of those. 但是,我得到的是在路径中的[]括号,我需要摆脱这些。

Here's what I'm getting: 这就是我得到的:

C:\\Program Files\\PostgreSQL\\[10.1]\\bin\\psql.exe

        root := "C:/Program Files/PostgreSQL"


        files, err := ioutil.ReadDir(root)
        if err != nil {
            return "", err
        }

        folders := []float64{}
        for _, f := range files {
            if f.IsDir() {
                if converted, err := strconv.ParseFloat(f.Name(),64); err == nil {
                    folders = append(folders, converted)
                }
            }
        }

        sort.Float64s(folders)

        log.Println(folders[len(folders)-1:])

        highestVersion := fmt.Sprintf("%v",folders[len(folders)-1:])

        execPath = filepath.Join(root, highestVersion, "bin", "psql.exe") 
        log.Println(execPath)

One possible approach would be to use a regular expression to ensure that each path has the expected format and to extract the version number as a float via a submatch (matching group), then sort the path strings by their floating point version number value and return the highest one. 一种可能的方法是使用正则表达式来确保每个路径都具有期望的格式,并通过子匹配(匹配组)将版本号提取为浮点,然后按其浮点版本号值对路径字符串进行排序并返回最高的。

For example: 例如:

func main() {
  paths := []string{
    `C:\Program Files\PostgreSQL\[1.2]\bin\psql.exe`,
    `C:\Program Files\PostgreSQL\[9.6]\bin\psql.exe`,
    `C:\Program Files\PostgreSQL\[10.1]\bin\psql.exe`,
    `C:\Program Files\PostgreSQL\[7.2]\bin\psql.exe`,
  }

  sort.Slice(paths, func(i, j int) bool {
    return parseVersion(paths[i]) >= parseVersion(paths[j])
  })
  fmt.Printf("OK: highest version path = %s\n", paths[0])
  // OK: highest version path = C:\Program Files\PostgreSQL\[10.1]\bin\psql.exe
}

var re = regexp.MustCompile(`C:\\Program Files\\PostgreSQL\\\[(\d+\.\d+)\]\\bin\\psql.exe`)

func parseVersion(s string) float32 {
  match := re.FindStringSubmatch(s)
  if match == nil {
    panic(fmt.Errorf("invalid path %q", s))
  }
  version, err := strconv.ParseFloat(match[1], 32)
  if err != nil {
    panic(err)
  }
  return float32(version)
}

Of course, you could modify the path regular expression to match different location patterns if that matters for your use case. 当然,如果这对您的用例很重要,则可以修改路径正则表达式以匹配不同的位置模式。

The issues are on this line: 问题在这条线上:

highestVersion := fmt.Sprintf("%v",folders[len(folders)-1:])

The %v format specifier, as some people have mentioned, is shorthand for "value". 正如某些人所提到的, %v格式说明符是“值”的简写。 Now let's look at your value: 现在让我们看看您的价值:

folders[len(folders)-1:]

What you are saying here is, "take a slice from folders starting at len(folders-1) ". 您在这里所说的是,“从以len(folders-1)开始的folders切片”。 Your variable is a slice that only contains the last item in folders . 您的变量是仅包含folders最后一项的切片。

Slices are printed by using brackets around the values, and since you have one value, it prints the value surrounded by square brackets. 通过在值周围使用方括号来打印切片,并且由于有一个值,因此它将打印由方括号括起来的值。

If you want to print just the float contained in that location, you should remove the colon as specified in a comment. 如果只想打印该位置中包含的浮点数,则应按照注释中的指定删除冒号。 I would recommend printing using the fmt verb %f or %g , depending on your use case. 我建议您使用fmt动词%f%g打印,具体取决于您的用例。

More information can be found in the pkg/fmt docs about what verbs are available to printf and other related functions. 可以在pkg / fmt文档中找到有关可用于printf和其他相关功能的动词的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM