-
-
Save davidvthecoder/10308388 to your computer and use it in GitHub Desktop.
package main | |
import ( | |
"log" | |
"math" | |
) | |
func Round(val float64, roundOn float64, places int ) (newVal float64) { | |
var round float64 | |
pow := math.Pow(10, float64(places)) | |
digit := pow * val | |
_, div := math.Modf(digit) | |
if div >= roundOn { | |
round = math.Ceil(digit) | |
} else { | |
round = math.Floor(digit) | |
} | |
newVal = round / pow | |
return | |
} | |
func main() { | |
log.Println(Round(123.555555, .5, 3)) | |
log.Println(Round(123.558, .5, 2)) | |
} |
I think the solution from @korya doesn't work for negative numbers. This one should do:
func(a float64) float64 {
if a < 0 {
return math.Ceil(a - 0.5)
}
return math.Floor(a + 0.5)
}
Thanks @DavidVaini
but the result is not the same as prevailing GUN c rint, e.g,
rint(1.5) -> 2
rint(2.5) -> 2
but we will get 2 and 3 with yours with roundOn = 0.5 and places = 0.
you can see the reference here http://www.gnu.org/software/libc/manual/html_node/Rounding.html
I just write a simple one here: https://gist.github.com/siddontang/1806573b9a8574989ccb
Note: this implementation fails for Round(-3.333, 0.5, 2)
-- expected -3.33
, got -3.34
Simple \sgn(y) \left\lfloor \left| y \right| + 0.5 \right\rfloor
would be enough.
After reading through many different and untested solutions, I decided to put together a package with implementations of ToEven
(used in .Net, Python 3) rounding and AwayFromZero
(used in Python 2) rounding.
It includes unit tests that demonstrate the expected behaviour of the implementation, and a comparison test with Python and a rough benchmark.
See https://github.com/a-h/round
Happy to take a pull request for ToPositiveInfinity
(used by Java) and ToNegativeInfinity
rounding if anyone cares about them.
hi guys, I never saw these comments until just now. The implementation was old and was something quick and dirty. Thus the code is in a gist snippet and not a repo. This worked for my case which was positive integers, but note it will fail with negative numbers. It looks like people have other implementations though they don't account for what decimal place you want to round on or what value you want to round on (.5 vs .9 or other use cases.
@korya +1
2018! -> https://golang.org/pkg/math/#Round
Without the math package: