MCPcopy
hub / github.com/montanaflynn/stats / Round

Function Round

round.go:6–38  ·  view source on GitHub ↗

Round a float to a specific decimal place or precision

(input float64, places int)

Source from the content-addressed store, hash-verified

4
5// Round a float to a specific decimal place or precision
6func Round(input float64, places int) (rounded float64, err error) {
7
8 // If the float is not a number
9 if math.IsNaN(input) {
10 return math.NaN(), NaNErr
11 }
12
13 // Find out the actual sign and correct the input for later
14 sign := 1.0
15 if input < 0 {
16 sign = -1
17 input *= -1
18 }
19
20 // Use the places arg to get the amount of precision wanted
21 precision := math.Pow(10, float64(places))
22
23 // Find the decimal place we are looking to round
24 digit := input * precision
25
26 // Get the actual decimal number as a fraction to be compared
27 _, decimal := math.Modf(digit)
28
29 // If the decimal is less than .5 we round down otherwise up
30 if decimal >= 0.5 {
31 rounded = math.Ceil(digit)
32 } else {
33 rounded = math.Floor(digit)
34 }
35
36 // Finally we do the math to actually create a rounded number
37 return rounded / precision * sign, nil
38}

Callers 13

TestGeometricMeanFunction · 0.92
TestHarmonicMeanFunction · 0.92
ExampleRoundFunction · 0.92
TestRoundFunction · 0.92
BenchmarkRoundFunction · 0.92
TestPopulationVarianceFunction · 0.92
ExampleCorrelationFunction · 0.92
mainFunction · 0.92

Calls

no outgoing calls

Tested by 11

TestGeometricMeanFunction · 0.74
TestHarmonicMeanFunction · 0.74
ExampleRoundFunction · 0.74
TestRoundFunction · 0.74
BenchmarkRoundFunction · 0.74
TestPopulationVarianceFunction · 0.74
ExampleCorrelationFunction · 0.74

Used in the wild real call sites across dependent graphs

searching dependent graphs…