将一个浮点数转换为一个字符串,而不是四舍五入 [英] Converting a float to a string without rounding it

查看:230
本文介绍了将一个浮点数转换为一个字符串,而不是四舍五入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个程序,因为不需要解释的原因,需要将一个浮点数转换为一个字符串来计算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'

Documentation here.

这篇关于将一个浮点数转换为一个字符串,而不是四舍五入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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