大多数Pythonic方式打印*最多*一些小数位

Most Pythonic way to print *at most* some number of decimal places(大多数Pythonic方式打印*最多*一些小数位)
本文介绍了大多数Pythonic方式打印*最多*一些小数位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我想格式化最多包含 2 个小数位的浮点数列表.但是,我不想要尾随零,也不想要尾随小数点.

I want to format a list of floating-point numbers with at most, say, 2 decimal places. But, I don't want trailing zeros, and I don't want trailing decimal points.

例如,4.001 => 4, 4.797 => 4.8, 8.992 => 8.99, 13.577 => 13.58.

So, for example, 4.001 => 4, 4.797 => 4.8, 8.992 => 8.99, 13.577 => 13.58.

简单的解决方案是('%.2f' % f).rstrip('.0')('%.2f' % f).rstrip('0').rstrip('.').但是,这看起来相当丑陋,而且似乎很脆弱.任何更好的解决方案,也许有一些神奇的格式标志?

The simple solution is ('%.2f' % f).rstrip('.0')('%.2f' % f).rstrip('0').rstrip('.'). But, that looks rather ugly and seems fragile. Any nicer solutions, maybe with some magical format flags?

推荐答案

需要将0.分开剥离;这样你就永远不会剥离自然的 0.

You need to separate the 0 and the . stripping; that way you won't ever strip away the natural 0.

或者,使用 format() 函数,但这实际上归结为同一件事:

Alternatively, use the format() function, but that really comes down to the same thing:

format(f, '.2f').rstrip('0').rstrip('.')

一些测试:

>>> def formatted(f): return format(f, '.2f').rstrip('0').rstrip('.')
... 
>>> formatted(0.0)
'0'
>>> formatted(4.797)
'4.8'
>>> formatted(4.001)
'4'
>>> formatted(13.577)
'13.58'
>>> formatted(0.000000000000000000001)
'0'
>>> formatted(10000000000)
'10000000000'

这篇关于大多数Pythonic方式打印*最多*一些小数位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)
Grouping pandas DataFrame by 10 minute intervals(按10分钟间隔对 pandas 数据帧进行分组)