You've fallen into a common trap. Base 2 floating point values cannot
represent most decimal values precisely. This is why you should never,
ever, do a simple equality test involving a F.P. value derived from a
calculation. You always have to apply an epsilon to define a range within
which the two F.P. values should be considered equal. The %v formatter does
something similar. The base 10 value 0.29 is actually
0.28999999999999998002 when stored base 2 (that's from printing a long
double var on a x86_64 platform).

Welcome to floating point pitfalls. Here be dragons!


On Sat, Jan 25, 2020 at 7:14 PM Jason E. Aten <j.e.a...@gmail.com> wrote:

>
> https://play.golang.org/p/87bDubJxjHO
>
> I'd like to truncate a float64 to just 2 decimal places (in base 10), but
> math.Trunc is not helping me here... ideally I put 0.29 in and I get 0.29
> out.
> Suggestions?  Playground examples appreciated.
>
> package main
>
> import (
> "fmt"
> "math"
> )
>
> // truncate off everything after the last two decimals, no rounding.
> func decimal2(x float64) float64 {
>     return math.Trunc(x*100) / 100
> }
>
> func main() {
>         x := 0.29
>         y := decimal2(x)
> fmt.Printf("x=%v -> y = %v", x, y) // prints x=0.29  ->  y=0.28
> }
>
> --
> You received this message because you are subscribed to the Google Groups
> "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to golang-nuts+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/golang-nuts/96528d64-a670-45ba-ad4c-0701dcd0d78d%40googlegroups.com
> <https://groups.google.com/d/msgid/golang-nuts/96528d64-a670-45ba-ad4c-0701dcd0d78d%40googlegroups.com?utm_medium=email&utm_source=footer>
> .
>


-- 
Kurtis Rader
Caretaker of the exceptional canines Junior and Hank

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/CABx2%3DD8JvQETOfkO63FWveyS7AbpKpLM1uVQsB6QH_mDNGajgw%40mail.gmail.com.

Reply via email to