繁体   English   中英

如何在Go中以Float64形式获取表单输入

[英]How to Get Form Input as Float64 in Go

我有一个使用Go构建的网络表单。 用户输入一个数字,然后我需要对该数字做一些数学运算。 似乎所有使用http包的方法都使用字符串作为输出。

如何在用户输入上进行简单的数学运算?

这是我的基本代码:

func init() {
    http.HandleFunc("/", root)
    http.HandleFunc("/result", result)
}

// handle the root url
func root(w http.ResponseWriter, r *http.Request) {
    fmt.Fprint(w, inputForm)
}

// root url html
const inputForm = `<html>
<body>
  <form action="/result" method="post">
    <div>Number between 0 and 1
       <input type="text" name="anar">
    </div>
  </form>
</body>
</html>
`

func result(w http.ResponseWriter, r *http.Request) {
    input := r.FormValue("anar")  // FormValue is always string

    // add number to input
    newNum := input + 0.25

    // stuff to output result
}

首先使用strconv.ParseFloat将输入转换为浮点数

fval, err := strconv.ParseFloat(input, 64)

if err != nil { 
    log.Println(err)
    //do something about it
}

newNum = fval + 0.25

一个朋友刚刚使用fmt软件包给了我这个答案。 我以为我也会分享。

type userInput struct {
    Num float64
}

input := "0.50"
s, err := fmt.Sscanf(input, "%f", &userInput.Num)
newNum := userInput.Num + 0.25

暂无
暂无

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

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