7

When multiplying golang float64 values with integers the result contains high precison error values due to the way floating point numbers are stored. Here is a code snippet that shows the problem I am referring to

package main

import (
"fmt"
)

func main() {
        var l float64 = 0.2
    fmt.Println("Hello, playground",l*6)
}

The result is

Hello, playground 1.2000000000000002

Here is the play link for the same playground

Is there a standard/best practise to round of the error ?

  • Related / possible duplicate of [Golang converting float64 to int error](http://stackoverflow.com/questions/36052922/golang-converting-float64-to-int-error) – icza Jun 20 '16 at 12:37

1 Answers1

0

It depends what the use case is and how many digits you want to show. You could do:

func main() {
    var l float64 = 0.2
    fmt.Printf("Hello, playground %.8f",l*6)
}

and only show 8 units after the decimal. But if you are dealing with currency, for example, you are better off not using floats at all, and saving everything as cents (in the US) or number of (lowest denomination of currency).

dave
  • 62,300
  • 5
  • 72
  • 93
  • I am dealing with currency in that case your point makes sense i should deal with lowest denominators but still i will have cases were internally we have to store even the lowest denominators as floating point values ie , one rate plan could be 0.2 cents per `unit` service where unit could be a second and i may store 7 seconds usage as 3.5 cents .Once we bill the customer only all these get added and rounded of to lowest denominator. I did not saw any Round function in golang math package so just wanted to know if there is any best practises used with general usecases – Sarath Sadasivan Pillai Jun 20 '16 at 06:50
  • 1
    WIth currency I would just avoid floats altogether. If that means you have to store rate as `uint64 hundredthsOfACent` and then the price they pay as `uint64 cents` that's fine. With money it's just better to completely avoid rounding errors. – dave Jun 20 '16 at 06:55
  • For currency calculation you might look for a 'decimal' package like https://github.com/EricLagergren/decimal – ABri Jun 20 '16 at 08:57
  • @dave great thanks , not using `float` was a great point to note . – Sarath Sadasivan Pillai Dec 29 '16 at 00:39