将一个浮点数转换为一个字符串,而不是四舍五入 [英] Converting a float to a string without rounding it
问题描述
我正在编写一个程序,因为不需要解释的原因,需要将一个浮点数转换为一个字符串来计算len()。但是,str(float(x))导致x在被转换为字符串时被舍入,从而抛出整个事情。有谁知道它的修复?
如果您想知道以下代码:
$ len $(str(float(x)/ 3) )
在处理某些形式的舍入时通常是不可避免的浮点数字。这是因为您可以精确地以10为基数表示的数字不能总是以2为底(即您的计算机使用的)来表示。
例如:
>>> .1
0.10000000000000001
在这种情况下,您将看到.1转换为字符串使用 repr
:
>>> repr(.1)
'0.10000000000000001'
我相信python会删除最后几位当你使用str()来解决这个问题时,这是一个部分的解决方法,不能代替理解正在发生的事情。
>>> str(.1)
'0.1'
我不确定究竟出了什么问题四舍五入正在导致你。也许你会更好地使用字符串格式化来更精确地控制你的输出?
$ b $例如
>>> '%.5f'%.1
'0.10000'
>>> '%.5f'%.12345678
'0.12346'
I'm making a program that, for reasons not needed to be explained, requires a float to be converted into a string to be counted with len(). However, str(float(x)) results in x being rounded when converted to a string, which throws the entire thing off. Does anyone know of a fix for it? Here's the code being used if you want to know:
len(str(float(x)/3))
Some form of rounding is often unavoidable when dealing with floating point numbers. This is because numbers that you can express exactly in base 10 cannot always be expressed exactly in base 2 (which your computer uses).
For example:
>>> .1
0.10000000000000001
In this case, you're seeing .1 converted to a string using repr
:
>>> repr(.1)
'0.10000000000000001'
I believe python chops off the last few digits when you use str() in order to work around this problem, but it's a partial workaround that doesn't substitute for understanding what's going on.
>>> str(.1)
'0.1'
I'm not sure exactly what problems "rounding" is causing you. Perhaps you would do better with string formatting as a way to more precisely control your output?
e.g.
>>> '%.5f' % .1
'0.10000'
>>> '%.5f' % .12345678
'0.12346'
这篇关于将一个浮点数转换为一个字符串,而不是四舍五入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!