Numbers
| Integers | |
| Floats | |
| The math package | |
| Random numbers |
Integers
The int type is the default choice for whole numbers: counters, indexes, sizes, and ages.
Integer division drops the remainder, and the percent operator returns it, so 7 divided by 2 gives 3 with a remainder of 1.
package main
import "fmt"
func main() {
total := 7 + 2 * 3
div := 7 / 2
rem := 7 % 2
fmt.Println(total, div, rem)
}
go run .
13 3 1
Floats
The float64 type stores fractional numbers such as prices, ratios, and coordinates.
Mixing int and float64 in one expression is not allowed, so convert the integer side explicitly before the operation.
package main
import "fmt"
func main() {
price := 19.99
count := 3
sum := price * float64(count)
fmt.Println(sum)
}
go run .
59.97
The math package
The math package provides roots, powers, rounding, trigonometry, and constants such as Pi.
Its functions take float64 values, which keeps numeric code uniform across the standard library.
package main
import (
"fmt"
"math"
)
func main() {
fmt.Println(math.Sqrt(16))
fmt.Println(math.Pow(2, 10))
fmt.Println(math.Pi)
}
go run .
4
1024
3.141592653589793
Random numbers
The math/rand package generates pseudo random numbers for games, tests, and simulations.
Recent Go versions seed the generator automatically, so Intn is ready to use without any setup call.
package main
import (
"fmt"
"math/rand"
)
func main() {
fmt.Println(rand.Intn(100))
fmt.Println(rand.Intn(100))
fmt.Println(rand.Float64())
}
Intn returns a value from 0 up to but not including the limit, while Float64 returns a value from 0.0 up to 1.0.
Next: Strings
Article author: Arthur Isaev