本文介绍了如何在python中加总位数(新格式)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在python中保持浮点数的总数(小数点前后).

I would like to keep the total number of digits (before and after the decimal point) of a float constant in python.

例如,如果我要施加7的固定宽度:1234.567890123会成为1234.567但12345.678901234会成为12345.67

For example, if I want to impose a fixed width of 7:1234.567890123would become1234.567but12345.678901234would become12345.67

在这种情况下,固定小数位数无效,因为这取决于我在小数点之前有多少位数.我也尝试过[width]选项,但是它设置了最小宽度,我需要最大宽度.

Fixing the number of decimals does not work in this case since it depends on how many digits I have before the decimal point. I also tried the [width] option but it impose a minimum width and I need a maximum.

感谢您的输入!

推荐答案

只需使用您的示例,

a = 1234.567890123 
b = 12345.678901234
str(a)[:8] # gives '1234.567'
str(b)[:8] # gives '12345.67'

这篇关于如何在python中加总位数(新格式)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 11:06