Go Reference ยท Time, Math and Randomness
Go math.Floor(), math.Ceil() and math.Round() functions
Reference for Go math.Floor, Ceil, Round, RoundToEven and Trunc: how each treats negative and halfway values, rounding to decimals and converting to int.
Go's math package has five functions that turn a float64 into a whole number (still stored as a float64): Floor rounds down, Ceil rounds up, Trunc cuts off the fraction toward zero, Round rounds to the nearest integer with halves going away from zero, and RoundToEven rounds halves to the nearest even number ("banker's rounding").
The difference shows up with negative numbers and with exact halves. There is no built-in function that rounds to a number of decimal places; you build it from Round with a scale factor.
fmt.Println(math.Floor(2.7), math.Ceil(2.1), math.Round(2.5)) // 2 3 3
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Syntax
func Floor(x float64) float64 func Ceil(x float64) float64 func Trunc(x float64) float64 func Round(x float64) float64 func RoundToEven(x float64) float64 func Modf(f float64) (int float64, frac float64)
| Function | 2.5 | -2.5 | Rule |
|---|---|---|---|
Floor |
2 | -3 | Largest whole number not above x. |
Ceil |
3 | -2 | Smallest whole number not below x. |
Trunc |
2 | -2 | Drop the fraction (toward zero). |
Round |
3 | -3 | Nearest; halves go away from zero. |
RoundToEven |
2 | -2 | Nearest; halves go to the even neighbour. |
Returns: a float64 with no fractional part. NaN and the infinities are returned unchanged. Modf returns the integer and fractional parts, both with the sign of the input.
Usage notes
Roundwas added in Go 1.10, and halves always move away from zero:Round(-0.5)is-1, whereasRoundToEven(-0.5)is negative zero.- Convert to
intonly after rounding.int(f)truncates toward zero and is undefined for NaN or values outside theintrange. - Floats cannot store most decimals exactly.
2.675is stored slightly below 2.675, so rounding it to two places gives 2.67 in many languages;Round(x*100)/100can also be off by one cent for such values. For money, store integer cents. fmtrounds for you.%.2frounds to the nearest representable decimal, which is usually the right thing for display and does not change the value.- Negative decimal places work with the
roundTohelper above:-2rounds to hundreds. - Integer ceiling division is
(a + b - 1) / bfor positive integers, avoiding floats. - Ceil and Floor of a huge float return the same value, since floats above 2^52 are already whole numbers.