我希望能够限制从打印功能显示的小数位数,而不需要任何类型的舍入系统
v = 8.836333333333339
print('%。2f'%v)
此代码会将v的值打印到两个小数位,但也会向上或向下舍入,我怎么能让它停止这个舍入呢?
答案 0 :(得分:1)
您可以将其作为字符串处理:
v = 8.836333333333339
s = str(v)
print s[:s.find('.')+3]
# prints 8.83
答案 1 :(得分:1)
如果您知道该数字的长度,您可以使用字符串切片轻松完成此操作。
>>> v = 8.836333333333339
>>> x = str(v) # get string representation of 'v'
>>> x
'8.836333333333339'
>>> y = x[0:4] # every character in 'x' between 0 and 4 but not including 4
>>> y
'8.83'
>>> v = float(y) # you can even convert it back to a number if you want
>>> v
8.83
答案 2 :(得分:0)
使用十进制模块怎么样:
>>> help(Decimal.quantize)
Help on method quantize in module decimal:
quantize(self, exp, rounding=None, context=None, watchexp=True) unbound decimal.Decimal
method
Quantize self so its exponent is the same as that of exp.
Similar to self._rescale(exp._exp) but with error checking.
>>> from decimal import *
>>> v = 8.834333333333339
>>> print Decimal(v).quantize(Decimal('0.01'))
8.83
>>> print Decimal('8.8663').quantize(Decimal('0.01'))
8.87
>>> print Decimal('8.863').quantize(Decimal('0.01'))
8.86
>>>
答案 3 :(得分:0)
有点针对您的情况,但您也可以使用int
来截断:
>>> print(int(v*100)/100.0)
8.83
它比基于find
字符串的方法快3倍(310 ns vs 925 ns)。
答案 4 :(得分:-1)
private void button2_Click(object sender, EventArgs e)
{
int X = 153;
int Y = 34;
for (int i = 1; i < 4; i++)
{
Panel pnl = new Panel();
pnl.SuspendLayout();
pnl.Location = new Point(X, Y);
pnl.Name = "pnl"+i;
pnl.Size = new Size(200, 57);
pnl.BorderStyle = BorderStyle.FixedSingle;
Label lbl = new Label();
lbl.Location = new Point(X - 100, Y - 17);
lbl.Name = "lbl" + i;
lbl.Size = new Size(75, 23);
lbl.Text = "lable_" +i;
pnl.Controls.Add(lbl);
pnl.ResumeLayout(false);
this.Controls.Add(pnl);
Y = Y + 95;
}
}
why not display label2 & label3?