How can we truncate float64 type to a particular precision?

前端 未结 12 1439
礼貌的吻别
礼貌的吻别 2021-02-02 05:33
package main

import (
    \"fmt\"
    \"strconv\"
    )

func main() {
    k := 10/3.0
    i := fmt.Sprintf(\"%.2f\", k)
    f,_ := strconv.ParseFloat(i, 2)
    fmt.Pri         


        
12条回答
  •  难免孤独
    2021-02-02 06:11

    No one has mentioned using math/big. The results as pertains to the original question are the same as the accepted answer, but if you are working with floats that require a degree of precision ($money$), then you should use big.Float.

    Per the original question:

    package main
    
    import (
        "math/big"
        "fmt"
    )
    
    func main() {
        // original question
        k := 10 / 3.0
        fmt.Println(big.NewFloat(k).Text('f', 2))
    }
    

    Unfortunately, you can see that .Text does not use the defined rounding mode (otherwise this answer might be more useful), but rather always seems to round toward zero:

    j := 0.045
    fmt.Println(big.NewFloat(j).SetMode(big.AwayFromZero).Text('f', 2)
    
    // out -> 0.04
    

    Nevertheless, there are certain advantages to having your float stored as a big.Float.

提交回复
热议问题