python - 格式化没有尾随零的 float

标签 python formatting floating-point pretty-print

如何格式化 float 以使其不包含尾随零?换句话说,我希望生成的字符串尽可能短。

例如:

3 -> "3"
3. -> "3"
3.0 -> "3"
3.1 -> "3.1"
3.14 -> "3.14"
3.140 -> "3.14"

最佳答案

我,我会这样做 ('%f' % x).rstrip('0').rstrip('.') -- 保证定点格式而不是科学记数法,等等等等。是的,不像 %g 那样圆滑优雅,但是,它可以工作(而且我不知道如何强制 %g 永远不要使用科学记数法; -)。

关于python - 格式化没有尾随零的 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2440692/

相关文章:

python - "import ... from ..."有性能优势吗?

python - 需要帮助了解如何实现内存

python - 安全 Python 登录

c - 如何在 C 中的 printf 中写入 .5?

Python Selenium - 属性错误 : WebElement object has no attribute sendKeys in textarea

javascript - 如何向 JSON 文件添加换行符以使其更具可读性?

C fscanf 如果解析为数字而不是字符串,则报告 EOF

ruby-on-rails - 在 FactoryGirl 中生成随机 float

c - 非规范化 float 被检测为 NaN。为什么?

string - 在 Haskell 中显示没有小数位的浮点整数的简单方法?