3

I want to convert a float64 number, let's say it 1.003 to 1003 (integer type). My implementation is simply multiply the float64 with 1000 and cast it to int.

package main

import "fmt"


func main() {
  var f float64 = 1.003
  fmt.Println(int(f * 1000))
}

But when I run that code, what I got is 1002 not 1003. Because Go automatically stores 1.003 as 1.002999... in the variable. What is the correct approach to do this kind of operation on Golang?

icza
  • 389,944
  • 63
  • 907
  • 827
Wendy Adi
  • 1,397
  • 3
  • 18
  • 26

3 Answers3

8

Go spec: Conversions:

Conversions between numeric types

When converting a floating-point number to an integer, the fraction is discarded (truncation towards zero).

So basically when you convert a floating-point number to an integer, only the integer part is kept.

If you just want to avoid errors arising from representing with finite bits, just add 0.5 to the number before converting it to int. No external libraries or function calls (from standard library) required.

Since float -> int conversion is not rounding but keeping the integer part, this will give you the desired result. Taking into consideration both the possible smaller and greater representation:

1002.9999 + 0.5 = 1003.4999;     integer part: 1003
1003.0001 + 0.5 = 1003.5001;     integer part: 1003

So simply just write:

var f float64 = 1.003
fmt.Println(int(f * 1000 + 0.5))

To wrap this into a function:

func toint(f float64) int {
    return int(f + 0.5)
}

// Using it:
fmt.Println(toint(f * 1000))

Try them on the Go Playground.

Note:

Be careful when you apply this in case of negative numbers! For example if you have a value of -1.003, then you probably want the result to be -1003. But if you add 0.5 to it:

-1002.9999 + 0.5 = -1002.4999;     integer part: -1002
-1003.0001 + 0.5 = -1002.5001;     integer part: -1002

So if you have negative numbers, you have to either:

  • subtract 0.5 instead of adding it
  • or add 0.5 but subtract 1 from the result

Incorporating this into our helper function:

func toint(f float64) int {
    if f < 0 {
        return int(f - 0.5)
    }
    return int(f + 0.5)
}
Community
  • 1
  • 1
icza
  • 389,944
  • 63
  • 907
  • 827
3

As Will mentions, this comes down to how floats are represented on various platforms. Essentially you need to round the float rather than let the default truncating behavior to happen. There's no standard library function for this, probably because there's a lot of possible behavior and it's trivial to implement.

If you knew you'd always have errors of the sort described, where you're slightly below (1299.999999) the value desired (1300.00000) you could use the math library's Ceil function:

f := 1.29999
n := math.Ceil(f*1000)

But if you have different kinds of floating error and want a more general sorting behavior? Use the math library's Modf function to separate the your floating point value by the decimal point:

f := 1.29999

f1,f2 := math.Modf(f*1000)
n := int(f1) // n = 1299   
if f2 > .5 { 
    n++
}
fmt.Println(n)

You can run a slightly more generalized version of this code in the playground yourself.

AndrewN
  • 425
  • 2
  • 6
0

This is probably likely a problem with floating points in general in most programming languages though some have different implementations than others. I wouldn't go into the intricacies here but most languages usually have a "decimal" approach either as a standard library or a third party library to get finer precision.

For instance, I've found the inf.v0 package largely useful. Underlying the library is a Dec struct that holds the exponents and the integer value. Therefore, it's able to hold 1.003 as 1003 * 10^-3. See below for an example:

package main

import (
    "fmt"

    "gopkg.in/inf.v0"
)

func main() {
    // represents 1003 * 10^-3
    someDec := inf.NewDec(1003, 3)

    // multiply someDec by 1000 * 10^0
    // which translates to 1003 * 10^-3 * 1000 * 10^0
    someDec.Mul(someDec, inf.NewDec(1000, 0))

    // inf.RoundHalfUp rounds half up in the 0th scale, eg. 0.5 rounds to 1
    value, ok := someDec.Round(someDec, 0, inf.RoundHalfUp).Unscaled()
    fmt.Println(value, ok)
}

Hope this helps!

Will C
  • 1,750
  • 10
  • 20
  • 1
    I've not used that package before, but looking at the docs, it certainly appears as if after rounding, you can call Unscaled() to extract an int value directly, rather than grabbing a string and converting it through strcon yet again. – AndrewN Oct 19 '15 at 03:57
  • Ah yes you're right. Totally forgotten that. Will update the code! Thanks! – Will C Oct 19 '15 at 04:09