On Wed, Oct 17, 2012 at 4:23 PM, Rory McGuire wrote:@Gerard missed the precision

Here is a combination of the solutions by Gerard and Jan Merci:

http://play.golang.org/p/ZmFfr07oHpPS: Anyone know for definite why Round(123.424999999999993, 2) gets wrong

result?

Float types have limited precisions, so you will inevitably get incorrect

results beyond a certain number of digits. If that is not acceptable for

your application, you probably shouldn't be using float types at all.

In your specific example, due to the lack of precision, float64 cannot

distinguish between 123.424999999999993 and 123.425000000000001:

http://play.golang.org/p/PAf89JrpYtSee also:

http://en.wikipedia.org/wiki/Floating_point#Accuracy_problemsShameless plug: you could try using the library I wrote for multi-precision

decimal arithmetic (project page:

http://code.google.com/p/godec/ ) .

Actually it doesn't (yet) have a method for "just rounding", but dividing

by 1 with scale 2 and half up rounding should give you the desired result.

(I might add a separate method for just rounding later, although I think in

most cases where rounding is needed it is in combination with a division

anyway.)

Here is an example:

package main

import "fmt"

import "code.google.com/p/godec/dec"

func main() {

d1, ok1 := new(dec.Dec).SetString("123.424999999999993")

d2, ok2 := new(dec.Dec).SetString("123.425000000000001")

if !ok1 || !ok2 {

panic("Invalid number")

}

one := dec.NewDecInt64(1)

r1 := new(dec.Dec).Quo(d1, one, dec.ScaleFixed2, dec.RoundHalfUp)

r2 := new(dec.Dec).Quo(d2, one, dec.ScaleFixed2, dec.RoundHalfUp)

fmt.Println(r1, r2)

}

Peter

On Tuesday, 16 October 2012 21:32:59 UTC+2, Gerard wrote:Op zondag 1 januari 2012 00:02:34 UTC+1 schreef Archos het volgende:

Is there any similar function to "round" in JavaScript?

To return the value of a number rounded to the nearest integer.

// round value - convert to int64

func Round(value float64) int64 {

if value < 0.0 {

value -= 0.5

} else {

value += 0.5

}

return int64(value)

}

--

--