将字符串转换为浮点型会失去精度吗? [英] Does converting a string to a float lose precision?

查看:111
本文介绍了将字符串转换为浮点型会失去精度吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

string 转换为 float64 时, float64 的小数部分丢失大量数字.

When converting a string to a float64, the fractional part of the float64 loses a significant amount of numbers.

origVal := "0.00000628"
convVal, err := strconv.ParseFloat(origVal, 64)
if err == nil {
    fmt.Printf("Original value: %s\nConverted value: %f\n", origVal, convVal)
}

输出:

Original value: 0.00000628
Converted value: 0.000006

该代码可在Go Play游乐场上找到: https://play.golang.org/p/a8fH_JGug7l

The code is available on the Go Playground: https://play.golang.org/p/a8fH_JGug7l

我正在从API中提取数据.该API对浮点数进行字符串化.我将这些字符串化的数字转换为浮点数,因为我想对它们进行一些基本的算术运算.
我对Go相当陌生,因此如果答案很简单,我深表歉意.

I am pulling data from an API. This API stringifies floating point numbers. I convert these stringified numbers to floats because I want to do some basic arithmetics on them.
I am fairly new to Go, so my apologies if the answer is straightforward.

推荐答案

问题不是不是未正确转换字符串,而是默认情况下 Printf 不会输出完整的小数部分如果很长.以下代码与原始代码打印相同,但小数点后有10个数字:

The problem was not that the string was not correctly converted, but that Printf does, by default, not output the complete fractional part if it is long. The following code prints the same as the original code but with 10 numbers after the decimal point:

origVal := "0.00000628"
convVal, err := strconv.ParseFloat(origVal, 64)
if err == nil && err2 ==nil {
    fmt.Printf("Original value: %s\nConverted value: %.10f\n", origVal, convVal)
}

感谢@ usr2564301的快速回复!

Thanks to @usr2564301 for the quick reply!

这篇关于将字符串转换为浮点型会失去精度吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆