Go: Converting float64 to int with multiplier

后端 未结 3 430
孤街浪徒
孤街浪徒 2021-01-14 05:42

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

相关标签:
3条回答
  • 2021-01-14 06:02

    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)
    }
    
    0 讨论(0)
  • 2021-01-14 06:13

    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!

    0 讨论(0)
  • 2021-01-14 06:15

    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.

    0 讨论(0)
提交回复
热议问题