Golang : Generate random integer or float number
Was helping out a friend last Sunday to finish up his Golang project and encounter a problem where we need to generate random integer or float number. Below is a snippet of the code that we used to generate the random numbers. Hope this can be useful to your work/project as well.
package main
import (
"math/rand"
"fmt"
)
func randSeed() (p []byte) {
for i := 0; i < 10; i++ {
p = append(p, byte(rand.Intn(512)))
}
return
}
func main() {
b := randSeed()
fmt.Println(b)
}
In case you are looking for random float number. This should do the trick :
fmt.Println(rand.Float64()) // rand.Float64 returns a float64 value f ... between 0.0 <= f < 1.0.
and if 0.0 to 1.0 is not what you wanted. You can tweak it to become in between 5.0 <= f < 10.0 with is this line
fmt.Print((rand.Float64() * 5) + 5)
Reference :
See also : Generate Random number with math/rand in Go
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
+6.1k Golang : Validate credit card example
+29.5k error: trying to remove "yum", which is protected
+5.5k Golang : How to determine if request or crawl is from Google robots
+14.1k Golang : How to add color to string?
+3.7k JavaScript : Rounding number to decimal formats to display currency
+4.8k Golang : Get Hokkien(福建话)/Min-nan(閩南語) Pronounciations
+7.8k Golang : How to extract video or image files from html source code
+13.7k Golang : Basic authentication with .htpasswd file
+9.3k RPM : error: db3 error(-30974) from dbenv->failchk: DB_RUNRECOVERY: Fatal error, run database recovery
+8.4k Golang : How to protect your source code from client, hosting company or hacker?
+14.4k Golang : Read large file with bufio.Scanner cause token too long error
+22.3k Golang : Use regular expression to validate domain name