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

String 如何在Go中以Float64形式获取表单输入,string,math,go,int,String,Math,Go,Int,我有一个使用Go构建的Web表单。用户输入一个数字,然后我需要对这个数字做一些计算。似乎所有使用http包的方法都使用字符串作为输出 如何对用户输入进行简单的计算 以下是我的基本代码: func init() { http.HandleFunc("/", root) http.HandleFunc("/result", result) } // handle the root url func root(w http.ResponseWriter, r *http.Reques

我有一个使用Go构建的Web表单。用户输入一个数字,然后我需要对这个数字做一些计算。似乎所有使用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
}
func init(){
http.HandleFunc(“/”,根)
http.HandleFunc(“/result”,result)
}
//处理根url
func root(w http.ResponseWriter,r*http.Request){
格式打印(w,输入格式)
}
//根url html
常量输入形式=`
介于0和1之间的数字
`
func结果(w http.ResponseWriter,r*http.Request){
输入:=r.FormValue(“anar”)//FormValue始终是字符串
//将数字添加到输入中
newNum:=输入+0.25
//填充以输出结果
}

首先使用


首先使用以下命令将输入转换为浮点


首先使用以下命令将输入转换为浮点


首先使用以下命令将输入转换为浮点


一位朋友刚刚用fmt软件包给了我这个答案。我想我也会分享它

type userInput struct {
    Num float64
}

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

一位朋友刚刚用fmt软件包给了我这个答案。我想我也会分享它

type userInput struct {
    Num float64
}

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

一位朋友刚刚用fmt软件包给了我这个答案。我想我也会分享它

type userInput struct {
    Num float64
}

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

一位朋友刚刚用fmt软件包给了我这个答案。我想我也会分享它

type userInput struct {
    Num float64
}

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

虽然这很好,但它比使用strconv慢得多,因为Sscanf必须解析输入、解析格式字符串并使用反射来分配值。虽然这很好,但它比使用strconv慢得多,因为Sscanf必须解析输入,解析格式字符串并使用反射来分配值。虽然这很好,但比使用strconv要慢得多,因为Sscanf必须解析输入,解析格式字符串并使用反射来分配值。虽然这很好,但比使用strconv慢得多,因为Sscanf必须解析输入,解析格式字符串并使用反射指定值。