简体   繁体   English

如何在Python中设置常规选项以在各处仅显示N位数字?

[英]How to set a general option in Python to display only N digits everywhere?

I want to work with 3 digits after the decimal point in Python. 我想在Python中使用小数点后的3位数字。 What is the relevant setting to modify ? 需要修改哪些相关设置?

I want that 1.0 / 3 would return 0.333, and not 0.3333333333333333 like it is the case in my Jupyter Notebook, using python 2.7.11 and Anaconda 4.0.0. 我希望1.0 / 3返回0.333,而不是0.3333333333333333,就像使用Python 2.7.11和Anaconda 4.0.0的Jupyter Notebook一样。

In my research, I heard about the Decimal class, but I don't want to use Decimal(x) in my code every time I display a float, neither the string formating or the round function, though I use it for the time being (because I don't want to use it every time). 在我的研究中,我听说了Decimal类,但是我不想每次显示浮点数时都在代码中使用Decimal(x),尽管我暂时不使用它格式化字符串或舍入函数。 (因为我不想每次都使用它)。

I think there is a general solution, a setting computed only once. 我认为有一个通用的解决方案,一个设置只计算一次。

use numpy and try this; 使用numpy尝试一下;

round(1.0/3, 3)

or 要么

>>> 1.0/3
0.3333333333333333

>>> '{:0.3f}'.format(1.0/3)
'0.333'

There is no "one-time" solution to your problem. 没有针对您的问题的“一次性”解决方案。 And I think that your approach might be a little misguided. 而且我认为您的方法可能会被误导。

I suppose that your interaction with Jupyter or Ipython has lead you to the conclusion that python is quite handy as a numerical calculator. 我想您与Jupyter或Ipython的互动已经使您得出结论,python作为数字计算器非常方便。 Unfortunately both of the aforementioned programs are just wrappers or REPL programs and in the background come with the full programming language flexibility that Python offers. 不幸的是,上述两个程序都是包装程序或REPL程序,并且在后台提供了Python提供的完整编程语言的灵活性。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在python中编写程序以生成仅以4和7为数字的所有n位数字? - How to write program in python to generate all n digit numbers with only 4 and 7 as their digits? 如何设置数据文件夹以便可以在python项目中的任何地方访问 - How to set up data folder to be accessible from everywhere in a python project 如何在 python 中只为 input().split() 设置 n 个输入? - How to set only n number of inputs for input().split() in python? 相同的 python 解释器,但 json_set 仅不适用于 Visual Studio Code,适用于其他任何地方 - Same python interpreter but json_set only not working on Visual Studio Code, works everywhere else Python-如何显示“ \\ n”? - Python - How to get “\n” to display? 如何在 Python 中复制 R 的 print(x, digits = n)? - How to copy R's print(x, digits = n) in Python? python 2.7-如何在分隔符为数字和'\\\\ n'时将字符串转换为列表 - python 2.7 - how to turn a string into a list when seperators are digits and '\\n' 如何在 python 中生成 N 次 function 并计算位数? - How to generate function n times in python and count digits? 如何形成给定数字的所有可能组合以形成不重复数字的n位数字?(python) - How to form all possible combination of given digits to form a n-digit number without repetition of digits?(python) 返回数字有多少位的函数digits(n),在python中返回一个随机值 - Function digits(n) that returns how many digits the number has , returns a random value in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM