我无法将混合字母和数字的字符串转换为带(或不带)小数的数字。字符串不一定是99,50,但也可以是任何其他字符串表示的数字。小数点分隔符也可以.代替,.我尝试了以下(游乐场链接):package mainimport ( "fmt" "strconv")func main() { price := "99,50 SEK" res1, _ := strconv.Atoi(price) fmt.Println(res1) res2, _ := strconv.ParseInt(price, 10, 64) fmt.Println(res2) res3, _ := strconv.ParseFloat(price, 64) fmt.Println(res3)}我从他们那里得到的输出是这样的:0我想要的输出是这样的:99.50也可以接受的是:99
1 回答

米琪卡哇伊
TA贡献1998条经验 获得超6个赞
您可以使用regexp包删除字母并替换,为.使用 ReplaceAll和解析
price := "99,50 SEK"
reg, _:= regexp.Compile("[^0-9,]+") // regex for digit and comma only
processedString := reg.ReplaceAllString(price , "") // remove all letters
processedString = strings.ReplaceAll(processedString, ",", ".") // replace comma with point
res3, _ := strconv.ParseFloat(processedString, 64)
操场代码在这里
- 1 回答
- 0 关注
- 109 浏览
添加回答
举报
0/150
提交
取消