如何截断/舍入十进制数? [英] How to truncate/round-off decimal numbers?

查看:60
本文介绍了如何截断/舍入十进制数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述




我想在小数点后截断每个数字到2位数。我b $ b尝试以下但是它不起作用。

Hi,

I want to truncate every number to 2 digits after the decimal point. I
tried the following but it doesnt work.

a = 2
b = 3
round(a * 1.0 / b,2)
a = 2
b = 3
round(a*1.0 / b,2)



0.67000000000000004


尽管在第二轮属性中指定2,但它会输出小数点后的所有

位数。


0.67000000000000004

Inspite of specifying 2 in 2nd attribute of round, it outputs all the
digits after decimal.

推荐答案

> ; >>> a = 2
> >>> a = 2
b = 3
round(a * 1.0 / b,2)0.67000000000000004

尽管在第二轮属性中指定2,但它会输出小数点后的所有数字。
b = 3
round(a*1.0 / b,2) 0.67000000000000004

Inspite of specifying 2 in 2nd attribute of round, it outputs all the
digits after decimal.




这是因为浮点不准确。系统无法准确地表示某些整数,但是它会尽力使用b $ b近似它们。请注意:



This is because of floating point inaccuracy. The system cannot
accurately represent some integers, however it does its best to
approximate them. Notice this:

x = 2.0 / 3
x
0.66666666666666663 round(x,2)
0.67000000000000004 s = str(round(x,2) ))
s
x = 2.0/3
x 0.66666666666666663 round(x,2) 0.67000000000000004 s = str(round(x,2))
s



''0.67''


''0.67''


>系统不能
准确地表示一些整数,




呃,我的意思是FLOATS。 Doh。


无论如何,只是为了强调这个例子:



Er, I meant FLOATS. Doh.

Anyway, just to underline the example:

x
0.66666666666666663 s = str(round(x,2))
s
''0.67''f = float(s)
f
0.67000000000000004 f == round(x,2)
x 0.66666666666666663 s = str(round(x,2))
s ''0.67'' f = float(s)
f 0.67000000000000004 f == round(x,2)



True


True


Girish Sahaniaécrit :
Girish Sahani a écrit :


我想在小数点后截断每个数字到2位数。我尝试了以下但是它不起作用。
Hi,

I want to truncate every number to 2 digits after the decimal point. I
tried the following but it doesnt work.
a = 2
b = 3
round(a * 1.0 / b,2)0.67000000000000004

尽管在第二轮属性中指定2,但它会输出小数点后的所有数字。
a = 2
b = 3
round(a*1.0 / b,2) 0.67000000000000004

Inspite of specifying 2 in 2nd attribute of round, it outputs all the
digits after decimal.




有两种操作:


1)计算round(),它返回一个浮点数结果,与

众所周知的问题浮点数represantation(参见常见问题解答)。


2)打印该数字,其中cli解释器中默认打印最后一个表达式结果

显示为最高精度,打印

语句的工作方式不同:



There are two operations:

1) calculate of round(), which return a float number result, with the
well known problem of floating point numbers represantation (see the FAQ).

2) print that number, where default printing of last expression result
in the cli interpreter displays up to the highest precision, print
statement works differently:

a = 2
b = 3
c = round(a * 1.0) / b,2)
c
0.67000000000000004 print c
0.67
a=2
b=3
c=round(a*1.0/b,2)
c 0.67000000000000004 print c 0.67




A +


Laurent。



A+

Laurent.


这篇关于如何截断/舍入十进制数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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