Skip to content

Instantly share code, notes, and snippets.

@pelegm
Forked from davidvthecoder/round.go
Last active January 5, 2018 13:48

Revisions

  1. pelegm revised this gist Oct 23, 2014. 1 changed file with 9 additions and 7 deletions.
    16 changes: 9 additions & 7 deletions round.go
    Original file line number Diff line number Diff line change
    @@ -1,25 +1,27 @@
    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 {
    _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
    }

    func main() {
    log.Println(Round(123.555555, .5, 3))
    log.Println(Round(123.558, .5, 2))
    }
    log.Println(Round(7.503300000000001e-05, .5, 5))
    log.Println(Round(-7.503300000000001e-05, .5, 5))
    }
  2. @davidvthecoder davidvthecoder created this gist Apr 9, 2014.
    25 changes: 25 additions & 0 deletions round.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,25 @@
    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))
    }