Round a float to a specific decimal place or precision
(input float64, places int)
| 4 | |
| 5 | // Round a float to a specific decimal place or precision |
| 6 | func 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 | } |
no outgoing calls
searching dependent graphs…