go.charczuk.com@v0.0.0-20240327042549-bc490516bd1a/sdk/mathutil/round_places.go (about)

     1  /*
     2  
     3  Copyright (c) 2023 - Present. Will Charczuk. All rights reserved.
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file at the root of the repository.
     5  
     6  */
     7  
     8  package mathutil
     9  
    10  import "math"
    11  
    12  // RoundPlaces a float to a specific decimal place or precision
    13  func RoundPlaces(input float64, places int) float64 {
    14  	if math.IsNaN(input) {
    15  		return 0.0
    16  	}
    17  
    18  	sign := 1.0
    19  	if input < 0 {
    20  		sign = -1
    21  		input *= -1
    22  	}
    23  
    24  	var rounded float64
    25  	precision := math.Pow(10, float64(places))
    26  	digit := input * precision
    27  	_, decimal := math.Modf(digit)
    28  
    29  	if decimal >= 0.5 {
    30  		rounded = math.Ceil(digit)
    31  	} else {
    32  		rounded = math.Floor(digit)
    33  	}
    34  	return rounded / precision * sign
    35  }