inancgumus/learngo · warning

Please provide a valid number

Error message

Please provide a valid number

What it means

parse() wraps strconv.ParseFloat: if the operand string cannot be parsed as a float64, it discards the underlying error and returns the friendly message "Please provide a valid number". It exists to give calculator users a readable validation error instead of strconv's verbose syntax errors.

Source

Thrown at x-tba/foundations/calc/08-funcs/main.go:54

	if b, err = parse(os.Args[3]); err != nil {
		fmt.Println(err)
		return
	}

	op := os.Args[2]
	res, err := calc(a, b, op)
	if err != nil {
		fmt.Println(err)
		return
	}

	fmt.Printf("%v %s %v = %v\n", a, op, b, res)
}

func parse(snum string) (n float64, err error) {
	n, err = strconv.ParseFloat(snum, 64)
	if err != nil {
		err = errors.New("Please provide a valid number")
	}
	return
}

func calc(a, b float64, op string) (res float64, err error) {
	switch op {
	case "+", "plus":
		op, res = "+", a+b
	case "-", "minus":
		op, res = "-", a-b
	case "*", "times":
		op, res = "*", a*b
	case "/", "div":
		op, res = "/", a/b
	case "%", "mod":
		res = float64(int(a) % int(b))
	default:
		return 0, errors.New("Wrong operation: '" + op + "'")

View on GitHub (pinned to 3c475a78e5)

Solutions

  1. Pass only valid numeric literals as the two operand arguments: calc 3.5 + 2.
  2. Quote operators to prevent shell globbing/expansion: calc 3 "*" 2.
  3. If the wrapped ParseFloat error is needed for debugging, wrap it instead of replacing it: fmt.Errorf("Please provide a valid number: %w", err).
  4. Use '.' as the decimal separator; ParseFloat does not accept comma decimals.
  5. Handle negative numbers as "-5" (accepted) but note hex/exponents like 0x10 or 1e2 behave per ParseFloat rules.

Example fix

// before
err = errors.New("Please provide a valid number")
// after
err = fmt.Errorf("Please provide a valid number: %w", err)
Defensive patterns

Strategy: validation

Validate before calling

n, err := strconv.ParseFloat(arg, 64)
if err != nil {
    fmt.Fprintf(os.Stderr, "Please provide a valid number: %s\n", arg)
    os.Exit(1)
}

Type guard

func isNumber(s string) bool {
    _, err := strconv.ParseFloat(s, 64)
    return err == nil
}

Try / catch

v, err := parse(arg)
if err != nil {
    if err.Error() == "Please provide a valid number" {
        fmt.Fprintf(os.Stderr, "usage: calc <num> <op> <num>\n")
        os.Exit(2)
    }
    panic(err)
}

Prevention

When it happens

Trigger: Running the calc program with an operand argument that is not a number, e.g. calc 3 + x, calc ten * 2, or an empty operand string.

Common situations: Typos on the command line, accidentally passing the operator in an operand slot, shells mangling arguments (e.g. '*' globbing), or locale-formatted numbers like "3,14".

Related errors


AI-assisted analysis of inancgumus/learngo@3c475a78e5 (2026-09-02). Data as JSON: /api/errors/4440619a3b699c49. Report an issue: GitHub.