我想要显示:
49 如 49.00
和:
54.9 如 54.90
无论小数的长度或是否有任何小数位,我想显示Decimal2位小数,我想以有效的方式做到这一点.目的是显示货币价值.
例如, 4898489.00
我该如何显示:
十进制('40800000000.00000000000000')为'4.08E + 10'?
我试过这个:
>>> '%E' % Decimal('40800000000.00000000000000')
'4.080000E+10'
Run Code Online (Sandbox Code Playgroud)
但它有额外的0.
如果我想让我的格式化字符串动态可调,我将更改以下代码
print '%20s : %20s' % ("Python", "Very Good")
Run Code Online (Sandbox Code Playgroud)
至
width = 20
print ('%' + str(width) + 's : %' + str(width) + 's') % ("Python", "Very Good")
Run Code Online (Sandbox Code Playgroud)
但是,似乎字符串连接在这里很麻烦.还有其他简化方法吗?
我有一个 pandas 数据框列,我希望将其格式化为小数点后两位。
这样:
10.1
显示为:
10.10
我怎样才能做到这一点?我已经尝试过四舍五入。
Currently I am trying to solve a problem, where I am supposed to print the answer upto two decimal points without rounding off. I have used the below code for this purpose
import math
a=1.175 #value of a after some division
print(math.floor(a*100)/100)
Run Code Online (Sandbox Code Playgroud)
The output we get is:
1.17 #Notice value which has two decimal points & not rounded
Run Code Online (Sandbox Code Playgroud)
但当我尝试打印一个可整除的数字时,真正的问题就开始了,小数点后只显示一个零。我使用了与上面相同的代码,但现在
a=25/5 #Now a is perfectly divisible
print(math.floor(a*100)/100)
Run Code Online (Sandbox Code Playgroud)
现在显示的输出是
5.0 #Notice only one decimal place is printed
Run Code Online (Sandbox Code Playgroud)
必须采取什么措施来纠正这个错误?
使用 % 格式,我可以四舍五入字符串中的小数位数:
pi = 3.14159265
print('pi = %0.2f' %pi)
Run Code Online (Sandbox Code Playgroud)
在输出中(在终端中)这会给我:
pi = 3.14
Run Code Online (Sandbox Code Playgroud)
我可以使用 f-strings 来完成这个任务吗?此功能已在 Python 3.6 中添加
python ×5
string ×2
decimal ×1
f-string ×1
fixed-point ×1
multiline ×1
pandas ×1
python-3.x ×1