Go: Converting float64 to int with multiplier

后端 未结 3 469
孤街浪徒
孤街浪徒 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)
    }
    

提交回复
热议问题