random Decimal in python

后端 未结 7 1157
野趣味
野趣味 2020-12-31 08:24

How do I get a random decimal.Decimal instance? It appears that the random module only returns floats which are a pita to convert to Decimals.

相关标签:
7条回答
  • 2020-12-31 09:21

    Yet another way to make a random decimal.

    import random
    round(random.randint(1, 1000) * random.random(), 2)
    

    On this example,

    • random.randint() generates random integer in specified range (inclusively),
    • random.random() generates random floating point number in the range (0.0, 1.0)
    • Finally, round() function will round the multiplication result of the abovementioned values multiplication (something long like 254.71921934351644) to the specified number after the decimal point (in our case we'd get 254.71)
    0 讨论(0)
提交回复
热议问题