大多数Pythonic打印方式*最多*小数位数 [英] Most Pythonic way to print *at most* some number of decimal places

查看:164
本文介绍了大多数Pythonic打印方式*最多*小数位数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想格式化一个浮点数的列表,最多是2个小数位。但是,我不想跟踪零,我不想跟踪小数点。

所以,例如, 4.001 => 4 4.797 => 4.8 8.992 => 8.99 , 13.577 => code> 13.58



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

解决方案

您需要分开 0

code>和剥离;这样你就不会剥夺自然 0



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

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

测试:

 >>> def format(f):return format(f,'.2f')。rstrip('0')。rstrip('。')
...
>>>格式化(0.0)
'0'
>>>格式化(4.797)
'4.8'
>>>格式化(4.001)
'4'
>>>格式化(13.577)
'13 .58'
>>>格式化(0.000000000000000000001)
'0'
>>>格式化(10000000000)
'10000000000'


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.

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

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?

解决方案

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

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

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

Some tests:

>>> 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打印方式*最多*小数位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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