doulu3865 2015-10-19 03:11
浏览 102
已采纳

转到:使用乘数将float64转换为int

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?

  • 写回答

3条回答 默认 最新

  • doulou0882 2015-10-19 07:00
    关注

    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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?