如何在Golang中将float64转换为十六进制字符串(遵循c99标准)?
-561.2863
至-0x1.18a4a57a786c2p9
答案 0 :(得分:1)
例如,
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)
}
游乐场:https://play.golang.org/p/9BygKkJcNbm
输出:
-561.2863
-0x.8c5252bd3c361p+10
-561.2862999999999829
-561.2862999999999829
或者,简单地
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)
}
游乐场:https://play.golang.org/p/MR2AxtlBcqv
输出:
-561.2863
-0x.8c5252bd3c361p+10
在C中,
#include <stdio.h>
int main() {
double f = -561.2863;
printf("%f %a\n", f, f);
}
输出:
-561.286300 -0x1.18a4a57a786c2p+9