Golang : Get digits from integer before and after given position example
This is more like just for fun tutorial, but can useful in a situation such as extracting suffix or prefix parts from phone numbers.
Problem:
You need to extract the last few digits from an integer, perform modulo operation or get first few digits from an integer without converting the integer into slice. How to do that?
Solution:
Use the modulo
%
(modulus) operand to get remainder or extract the first few digits by division
/
.
Here you go! Happy coding!
package main
import (
"fmt"
)
func main() {
num := 12345
lastThreeDigits := num % 1e3 // use modulo to "count" from back
// length of num is 5
firstTwoDigits := num / 1e3 // cut off after position 3
fmt.Println("Number is : ", num)
fmt.Println("Last 3 digits is : ", lastThreeDigits)
fmt.Println("First 2 digits is : ", firstTwoDigits)
// if num is 1234567
num = 1234567
fmt.Println("Number is : ", num)
firstThreeDigits := num / 1e4 // cut off after position 4
fmt.Println("First 3 digits is : ", firstThreeDigits)
lastFourDigits := num % 1e4
fmt.Println("Last 4 digits is : ", lastFourDigits)
fmt.Println("By the way, 1e3 stands for ", 1e3)
fmt.Println("and 1e4 stands for ", 1e4)
}
Output:
Number is : 12345
Last 3 digits is : 345
First 2 digits is : 12
Number is : 1234567
First 3 digits is : 123
Last 4 digits is : 4567
By the way, 1e3 stands for 1000
and 1e4 stands for 10000
References:
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+5.2k Golang : Intercept, inject and replay HTTP traffics from web server
+31.3k Golang : How to convert(cast) string to IP address?
+16.3k Golang : Merge video(OpenCV) and audio(PortAudio) into a mp4 file
+11.4k Golang : Surveillance with web camera and OpenCV
+8.3k Android Studio : Import third-party library or package into Gradle Scripts
+5.9k Golang : Extract XML attribute data with attr field tag example
+12.4k Golang : Add ASCII art to command line application launching process
+12.4k Golang : Drop cookie to visitor's browser and http.SetCookie() example
+19.6k Golang : Accept input from user with fmt.Scanf skipped white spaces and how to fix it
+9.1k Golang : Launch Mac OS X Preview (or other OS) application from your program example
+8.4k Golang : Convert(cast) []byte to io.Reader type
+6.2k PHP : Proper way to get UTF-8 character or string length