使用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

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

You may want to use a Decimal64p2 type of decimal with fixed .00 precision - https://github.com/strongo/decimal

It is efficient for storing exact amounts of money.

Try this:

f := 5.8
ipart := int64(f)
fmt.Println(ipart)
decpart := fmt.Sprintf("%.7g", f-float64(ipart))[2:]
fmt.Println(decpart)

The complete answer in available in go playground. Basically I used the format specifier %g to achieve the result, moreover, %.6g rounds the decimal part to six places, trailing zeroes are not shown.

Documentation of fmt package