duanhe6718
duanhe6718
2018-07-25 19:32
浏览 126
已采纳

如何在Golang中将float64转换为c99十六进制字符串?

How to convert float64 to hex string(that follows c99 standard) in Golang?

-561.2863 to -0x1.18a4a57a786c2p9

图片转代码服务由CSDN问答提供 功能建议

如何在Golang中将float64转换为十六进制字符串(遵循c99标准)?

-561.2863 -0x1.18a4a57a786c2p9

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doukao1925
    doukao1925 2018-07-25 20:19
    已采纳

    For example,

    package main
    
    import (
        "fmt"
        "math/big"
    )
    
    func main() {
        f := new(big.Float).SetFloat64(-561.2863)
        fmt.Println(f)
        t := f.Text('p', 0)
        fmt.Println(t)
        g, ok := new(big.Float).SetString(t)
        if !ok {
            fmt.Println("error")
        }
        fmt.Println(g)
        c, ok := new(big.Float).SetString("-0x1.18a4a57a786c2p9")
        if !ok {
            fmt.Println("error")
        }
        fmt.Println(c)
    }
    

    Playground: https://play.golang.org/p/9BygKkJcNbm

    Output:

    -561.2863
    -0x.8c5252bd3c361p+10
    -561.2862999999999829
    -561.2862999999999829
    

    Or, simply,

    package main
    
    import (
        "fmt"
        "math/big"
    )
    
    func main() {
        f64 := -561.2863
        fmt.Println(f64)
        s := new(big.Float).SetFloat64(f64).Text('p', 0)
        fmt.Println(s)
    }
    

    Playground: https://play.golang.org/p/MR2AxtlBcqv

    Output:

    -561.2863
    -0x.8c5252bd3c361p+10
    

    In C,

    #include <stdio.h>
    
    int main() {
        double f = -561.2863;
        printf("%f %a
    ", f, f);
    }
    

    Output:

    -561.286300 -0x1.18a4a57a786c2p+9
    
    点赞 评论

相关推荐