typestar

strconv in Go

Text to number and back, with the error you must handle.

func conversions(text string) ([]string, error) {
    n, err := strconv.Atoi(text)
    if err != nil {
        return nil, fmt.Errorf("atoi %q: %w", text, err)
    }

    hex, err := strconv.ParseInt("ff", 16, 64)
    if err != nil {
        return nil, err
    }

    return []string{
        strconv.Itoa(n * 2),
        strconv.FormatInt(hex, 10),
        strconv.FormatFloat(1.0/3.0, 'f', 4, 64),
        strconv.Quote("tab\there"),
        strconv.FormatBool(n > 0),
    }, nil
}

How it works

  1. Atoi is the shorthand; ParseInt takes a base and a size.
  2. ParseFloat and ParseBool complete the set.
  3. Quote escapes a string the way Go source would.

Keywords and builtins used here

The run, in numbers

Lines
19
Characters to type
396
Tokens
125
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 71 seconds.

Type this snippet

Step 4 of 5 in Collections & text, step 12 of 26 in Standard library & project layout.

← Previous Next →