dsfb20227 2016-10-20 00:47 采纳率: 0%
浏览 1284

使用golang分隔整数和小数部分

I'm new to Golang. I wanted to separate a floating point number into whole and decimal parts. After some research I implemented it but there is a problem in my code. I'm using 5.8 as the input but the result is 5 and 0.79999.

package main

import(
        "fmt"
        "math"
)    

func Round2(val float64) {
        intpart, div := math.Modf(val)
        fmt.Println(div)

        fmt.Println(intpart)

}

func main() {
        fmt.Println("Hello, playground")
        Round2(5.8)
}

I have tried this, I'm getting an output of:

0.7999999999999998
5

If there is any other way to do this please let me know. I have inserted the go playground with my code in it.

https://play.golang.org/p/O4n0k0XyMX

  • 写回答

3条回答 默认 最新

  • dongya1875 2016-10-20 02:55
    关注

    This is an artifact of floating-point arithmetic. A floating-point value is not always exactly the value you expect it to be due to the fact that not all numbers can be represented exactly in the floating-point format used by whatever processor you happen to be using. Obviously, the value is very close to 0.8 and is equal to 15 significant figures. Note that this is not specific to Go.

    Instead of

    fmt.Println(div)
    

    try

    fmt.Printf(".4f
    ", div) // shows only 4 decimal places
    

    It looks like this article has some good information: https://en.wikipedia.org/wiki/Floating_point#Accuracy_problems

    评论

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路