ashirley - 6 months ago 99

Python Question

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

Answer

What's "a random decimal"? Decimals have arbitrary precision, so generating a number with as much randomness as you can hold in a Decimal would take the entire memory of your machine to store.

You have to know how many decimal digits of precision you want in your random number, at which point it's easy to just grab an random integer and divide it. For example if you want two digits above the point and two digits in the fraction (see randrange here):

```
decimal.Decimal(random.randrange(10000))/100
```