Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,903 questions

51,834 answers

573 users

How to get the first x leftmost digits of an integer number in Go

1 Answer

0 votes
package main

import (
	"fmt"
	"math"
	"math/rand"
	"time"
)

func xLeftmostDigit(n int, x int) int {
	xPow := int(math.Pow(10, float64(x)))
	for n > xPow {
		n = n / 10
	}
	return n
}

func main() {
	rand.Seed(time.Now().UnixNano())
	for i := 1; i <= 5; i++ {
		n := rand.Intn(100000) + 1
		x := rand.Intn(5) + 1
		fmt.Printf("%d leftmost digit of %d is %d\n", x, n, xLeftmostDigit(n, x))
	}
}



/*
run:

2 leftmost digit of 83449 is 83
3 leftmost digit of 30027 is 300
4 leftmost digit of 67830 is 6783
1 leftmost digit of 25694 is 2
3 leftmost digit of 63331 is 633

*/

 



answered Dec 8, 2024 by avibootz
...