The round package provides a simple and efficient way to round floating-point numbers to a specified number of decimal places in Go. It leverages the Go standard library's math package to perform its calculations.
To use the round package in your Go project, first, ensure you have Go installed on your system. Then, you can install the package by adding it to your project's dependencies:
go get -u github.com/bronekot/go-roundHere's how you can use the round package to round a floating-point number:
package main
import (
"fmt"
"github.com/yourusername/round" // Replace with the actual import path
)
func main() {
roundedValue := round.Round(3.14159, 2)
fmt.Println(roundedValue) // Output: 3.14
}The Round function is the core of this package. Here's its signature:
func Round(x float64, prec int) float64Parameters:
x: The floating-point number you want to round.prec: The number of decimal places to roundxto.
Returns:
- The rounded value of
xtoprecdecimal places.
The Round function rounds a floating-point number x to prec decimal places. It does this by:
- Multiplying
xby 10 raised to the power ofprec. - Separating the result into its integer and fractional parts.
- If the fractional part is 0.5 or greater, or if it's between -0.5 and 0 (inclusive) for negative numbers, it rounds up by using the
Ceilfunction. Otherwise, it rounds down using theFloorfunction. - Dividing the result by 10 raised to the power of
precto adjust the value back to the original scale.
Contributions to improve the round package are welcome. Please feel free to submit issues and pull requests through the GitHub repository.
This package is released under the MIT License. See the LICENSE file for details.