// Copyright 2018 Bull S.A.S. Atos Technologies - Bull, Rue Jean Jaures, B.P.68, 78340, Les Clayes-sous-Bois, France. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package mathutil import "math" // Round rounds a value val starting at roundOn, and keep places decimal // Round(123.555555, .5, 3) -> 123.556 // Round(123.558, .5, 2) -> 123.56 // Round(123.00001, 0, 0) -> 124 // // Credits to https://gist.github.com/pelegm/c48cff315cd223f7cf7b 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) _div := math.Copysign(div, val) _roundOn := math.Copysign(roundOn, val) if _div >= _roundOn { round = math.Ceil(digit) } else { round = math.Floor(digit) } newVal = round / pow return }