如何格式化 python 中小数点后零个数可变的浮点数?

How to format a float in python which has variable number of zeros after decimal point?

我有一个函数 returns 一个浮点数,小数点后可以有 0 到最多 8 个零。

我想将浮点数格式化为非科学记数法,并只显示小数点后跟在零之后的最多 4 个非零数字。

例如:

1.42 should be formatted as 1.42  
1.4205152 should be formatted as 1.4205  
1.42e-2 should be formatted as 0.0142  
1.452e-4 should be formatted as 0.0001452  
1.49315e-5 should be formatted as 0.00001493  

python 中是否有格式说明符可以这样做,或者编写自定义函数是唯一的解决方案?

没有对此的内置支持。也就是说,没有直接执行此操作的格式说明符或转换函数。您将需要编写自己的代码来进行格式化。