round

package module
v0.0.0-...-1ebe1c0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 17, 2017 License: MIT Imports: 1 Imported by: 7

README

Rounding

Why!? Because Go's math package doesn't include a Round() function.

All of the implementations I saw lacked unit tests or comments to make it easy to understand, so I made one and tested it.

There are two functions:

  • ToEven
    • Default in Python 3 and C#
    • -3.5 = -4
    • -2.5 = -2
    • -1.5 = -2
    • 1.5 = 2
    • 2.5 = 2
    • 3.5 = 4
  • AwayFromZero
    • Default in Python 2
    • -3.5 = -4
    • -2.5 = -3
    • -1.5 = -2
    • 1.5 = 2
    • 2.5 = 3
    • 3.5 = 4

How to use

go get github.com/a-h/round
import "github.com/a-h/round"

func main() {
    fmt.Println(round.ToEven(float64(-3.5), 0)) // -4
    fmt.Println(round.ToEven(float64(-2.5), 0)) // -2
    fmt.Println(round.ToEven(float64(-1.5), 0)) // -2
    fmt.Println(round.ToEven(float64(-1.49), 0)) // -1
}

Reference

Learn about Rounding Methods.

Issue on Github asking for a float function.

Discussion on Go forum discussing how to Round, and not really reaching consensus.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AwayFromZero

func AwayFromZero(v float64, decimals int) float64

AwayFromZero rounds numbers away from zero. Used in Python 2 (but not Python 3, which uses ToEven). -3.5 rounds to -4 -2.5 rounds to -3 -1.5 rounds to -2 1.5 rounds to 2 2.5 rounds to 3 3.5 rounds to 4

func ToEven

func ToEven(v float64, decimals int) float64

ToEven rounds to the nearest even number. Used in Python 3 (but not Python 2, which uses AwayFromZero). -3.5 rounds to -4 -2.5 rounds to -2 -1.5 rounds to -2 1.5 rounds to 2 2.5 rounds to 2 3.5 rounds to 4

Types

This section is empty.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL