0

I have this variable:

danumber := "542353242"

and want to extract a character from the string and operate with it as a number. Tried this:

int(danumber[0])

but it doesn't seem to work.

1
  • 1
    What is the expected result of this supposed operation? 5 or 53 (an US-ASCII code for the character "5")? I'm asking because "extract a character ... and operate with it as a number" can be interpreted as if you'd like to get the character code and not convert "5" to an integer 5. Commented Jan 22, 2016 at 18:13

1 Answer 1

4

What your expression gives you is the character code for the digit. To convert the character to the character's value, subtract 0's character code from it:

int(danumber[0] - '0') // in your example, this is: 53 - 48

If you want to convert multiple digits, I would recommend using the strconv package:

number, err := strconv.Atoi(danumber[0:2]) // convert first two characters to int
Sign up to request clarification or add additional context in comments.

2 Comments

thanx, I'll try it. Could you explain why would this work? What about a sub string like danumber[0:3] ?
@Perroloco: Updated. Yes, danumber[0:3] would work as well with strconv.Atoi.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.