Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract digits at a certain position in a number

Tags:

go

number := 111555

How do I get, for instance the first 3 digits (111) and the last 2 digits (55)?

like image 487
Sergey Onishchenko Avatar asked Oct 15 '17 09:10

Sergey Onishchenko


People also ask

How do you isolate digits in Java?

You can convert a number into String and then you can use toCharArray() or split() method to separate the number into digits. String number = String. valueOf(someInt); char[] digits1 = number.


2 Answers

By using simple arithmetic:

func d(num int) (firstThree int, lastTwo int) {
    firstThree = num / 1000
    lastTwo = num % 100
    return
}
like image 150
augustzf Avatar answered Sep 16 '22 12:09

augustzf


This function gives the digit at a specific place:

func digit(num, place int) int {
    r := num % int(math.Pow(10, float64(place)))
    return r / int(math.Pow(10, float64(place-1)))
}

For example digit(1234567890, 2) gives 9 and digit(1234567890, 6) gives 5.

like image 30
Kaveh Shahbazian Avatar answered Sep 17 '22 12:09

Kaveh Shahbazian