Home > front end >  Input validation in golang
Input validation in golang

Time:10-20

Here is my code snippet and i dont know how to validate input data type in number1 and number2 variables. I need them to be float64 digits but not a string or other type. I've read about try catch, but I don't know how to use them here. Or is there an easier way of validation?

package main

import (
    "fmt"
    "math"
)

func main() {
    var number1, number2 float64
    var operator string

fmt.Print("Enter the first number: ")
fmt.Scanln(&number1)

fmt.Print("Enter the second number: ")
fmt.Scanln(&number2)

fmt.Print("Enter the operator  , -, *, /, **: ")
fmt.Scanln(&operator)

CodePudding user response:

You can check if a string value is a correct float64 using the strconf.ParseFloat function

f, err := strconv.ParseFloat("4.56", 64)
if err != nil {
    fmt.Println("The value is not a valid float!")
    return
}
fmt.Print(f)
  • Related