string - 如何在 Go 中将表单输入作为 Float64

标签 string math go int

我有一个使用 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 将输入转换为 float

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

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

newNum = fval + 0.25

关于string - 如何在 Go 中将表单输入作为 Float64,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25070475/

相关文章:

C 读取字符串而不是文件

c - GTK 字符数与字节索引

c++ - 系统::字符串转ASCII码

c# - 在 C# 中实现 De Boor 样条算法

java - SimpleDateFormat:如何正确格式化包含字母 T 的日期字符串?

algorithm - n!在 n^100 log n 中可实现的不同排列

javascript - 随机映射div

使用 slice 类型的输入和输出 channel 去并发工作例程

error-handling - 为什么我不能把左大括号放在下一行?

go - slice 内容的大小(以字节为单位)