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
...