dsaob80228 2014-01-19 18:10
浏览 432

GO:处理随机生成的float64

I was wondering if we can specify to the random generator to how many numbers should be generated after the point decimal?

Example of default behaviour:

fmt.Println(rand.float64())

Would print out the number 0.6046602879796196

Desired behaviour:

fmt.Println(rand.float64(4))

Would then print out the number 0.6047.

Does this functionality already exist in GO or would I have to implement it myself ?

Thank you!

  • 写回答

2条回答 默认 最新

  • doukai2839 2014-01-19 18:23
    关注

    It sounds like only the string representation is important to you, and the fmt package does provide that for you:

    fmt.Printf("%1.4f", rand.Float64())
    

    So yes, you would still need to wrap this call to specify the number of digits after the decimal point.

    func RandomDigits(number int) string {
        return fmt.Sprintf("%1." + strconv.Itoa(number) + "f", rand.Float64())
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法