将混合了数字和字母的字符串转换为数字

我无法将混合字母和数字的字符串转换为带(或不带)小数的数字。字符串不一定是99,50,但也可以是任何其他字符串表示的数字。小数点分隔符也可以.代替,.


我尝试了以下(游乐场链接):


package main

import (

    "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


交互式爱情
浏览 110回答 1
1回答

米琪卡哇伊

您可以使用regexp包删除字母并替换,为.使用 ReplaceAll和解析price := "99,50 SEK"    reg, _:= regexp.Compile("[^0-9,]+") // regex for digit and comma onlyprocessedString := reg.ReplaceAllString(price , "") // remove all letters processedString = strings.ReplaceAll(processedString, ",", ".") // replace comma with pointres3, _ := strconv.ParseFloat(processedString, 64)操场代码在这里
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go