dongzhuang1923 2011-11-09 19:07
浏览 1506
已采纳

从Go中的float32转换为int

I have tried several ways to cast a float to an int, what I want is to truncate a float so I only get the integer part. I'm using

x := float32(3.1)
y,_ := strconv.Atoi((strconv.Ftoa32(x,'f',0))) //y becomes 3

But if x is 3.9, y will become 4 because this function will round the float32 instead of truncating. Is there a way of truncating instead of rounding? and if so, is it possible to do it without involving strings? (like casting a float to int in C)

  • 写回答

1条回答 默认 最新

  • duan198123 2011-11-09 19:19
    关注

    Just use int():

    x := float32(3.1)
    fmt.Println(int(x))
    

    Which produces 3 as needed, without having to use string conversions or the like.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比