Skip to content

Instantly share code, notes, and snippets.

@shirou
Created July 26, 2024 04:10
Show Gist options
  • Save shirou/7a9704cd78ff2ee92a7d161e24dd3a35 to your computer and use it in GitHub Desktop.
Save shirou/7a9704cd78ff2ee92a7d161e24dd3a35 to your computer and use it in GitHub Desktop.
convert from float32 to float64 with same precision.
// float32Tofloat64は同じ小数点以下桁数を持つfloat64を返す
func float32Tofloat64(f32 float32) float64 {
// 小数点以下何桁かを調べるために文字列に変換。7はfloat32の有効桁数
strF32 := fmt.Sprintf("%.7g", f32)
// .からの文字数を取得
pos := 0
for i := 0; i < len(strF32); i++ {
if strF32[i] == '.' {
pos = len(strF32) - i - 1
break
}
}
f64 := float64(f32)
factor := math.Pow(10, float64(pos))
return math.Round(f64*factor) / factor
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment