Go: Converting float64 to int with multiplier

后端 未结 3 456
孤街浪徒
孤街浪徒 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: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.

提交回复
热议问题