我如何将字符串转换为整数而不从开头删除0位前缀。像这样的用例,我有一个像“0093”的字符串,我想将其与0093转换为整数。我尝试使用strconv,但问题是此程序包在转换后从0093删除了00前缀。任何人都可以对这个问题有更好的解决方案。

s := "0093"
  if i, err := strconv.Atoi(s); err == nil {
  fmt.Printf("i=%d, type: %T\n", i, i)
}

输出为93,但我想要int类型的0093。

最佳答案

fmt包的文档中:

Width is specified by an optional decimal number immediately preceding the verb. If absent, the width is whatever is necessary to represent the value.
...
Other flags:
0   pad with leading zeros rather than spaces;
    for numbers, this moves the padding after the sign

https://golang.org/pkg/fmt/

如果将这两件事结合在一起,那么您将获得代码:
fmt.Printf("i=%04d, type: %T\n", i, i)

https://play.golang.org/p/lR77KoCswv_B

10-06 13:16