本文介绍了Go:将float64转换为带有乘数的int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想转换一个 float64 数字,假设它是 1.003 1003 (整型)。我的实现只是将 float64 1000 相乘,并将其转换为 int $ b $ pre $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
func main(){
var f float64 = 1.003
fmt.Println(int(f * 1000))
}

但是当我运行这个代码时,得到的是 1002 不是 1003 。由于Go自动将 1.003 存储为变量中的 1.002999 ... 。在Golang上做这种操作的正确方法是什么?

解决方案


$ b

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)
}

这篇关于Go:将float64转换为带有乘数的int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 05:07