【问题标题】:How to Get Form Input as Float64 in Go如何在 Go 中获取表单输入为 Float64
【发布时间】:2014-09-24 01:57:10
【问题描述】:

我有一个使用 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
}

【问题讨论】:

    标签: string math go int


    【解决方案1】:

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

    fval, err := strconv.ParseFloat(input, 64)
    
    if err != nil { 
        log.Println(err)
        //do something about it
    }
    
    newNum = fval + 0.25
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 虽然这工作得很好,但它会比使用 strconv 慢得多,因为 Sscanf 必须解析输入,解析格式字符串并使用反射来分配值。
      猜你喜欢
      • 1970-01-01
      • 2022-01-22
      • 2011-12-22
      • 1970-01-01
      • 2012-06-05
      • 1970-01-01
      • 1970-01-01
      • 2010-11-15
      • 2020-01-23
      相关资源
      最近更新 更多