How to convert float64 to hex string(that follows c99 standard) in Golang?
-561.2863
to -0x1.18a4a57a786c2p9
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\n", f, f);
}
Output:
-561.286300 -0x1.18a4a57a786c2p+9
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments