python - 如何在 Python 中使用 x DP 将分数写为十进制?

标签 python printing decimal precision fractions

我正在寻找的是一种将 python Fraction() 类型写出到任意小数位的方法。我查看了分数和小数的 python 文档,但我看不到任何转换或写出分数的方法。

所以我要找的是一些打印出来的方法

Fraction(5, 7)

作为

0.7142857142857142857142857142857142857142857142857142

代替

>> float(Fraction(5, 7))
0.7142857142857143

指定 DP 的数量。

最佳答案

您可以使用 Decimal 获得任意精度类。

from fractions import Fraction
from decimal import localcontext, Decimal

def print_fraction(f, digits):
    assert(f.imag == 0)

    # Automatically reset the Decimal settings
    with localcontext() as ctx:
        ctx.prec = digits
        print(Decimal(f.numerator) / Decimal(f.denominator))

f = Fraction(5, 7)
print_fraction(f, 52)

这将打印 0.7142857142857142857142857142857142857142857142857143

关于python - 如何在 Python 中使用 x DP 将分数写为十进制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11154954/

相关文章:

python - 通过子字符串搜索连接 pyspark 中的两个数据帧

hex - 十进制 <--> 二进制补码 <--> 十六进制转换

python - 如何获得没有小数位的数字?

html - 打印对齐和定位标题

javascript - javascript中如何处理大数字

python - 如何在访问者指定的日期发送电子邮件?

python - 使用 pybind11 将 NumPy 数组转换到自定义 C++ 矩阵类或从自定义 C++ 矩阵类转换

python - 在应用程序中嵌入远程 Python shell

python - 以某种格式打印 float 组

windows - 通过 Get-WmiObject : Exception calling SetDefaultPrinter : Not Supported 设置默认打印机时出错