darkhorse
darkhorse

Reputation: 8742

Creating the maximum possible decimal number from a given number of max digits and decimal places in Python

Given max_digits and decimal_places, the method will return the maximum possible decimal number. The following is my code right now:

from decimal import Decimal

def get_max_decimal_number(max_digits, decimal_places):
    result = ''

    for i in range(max_digits - decimal_places):
        result += '9'

    if decimal_places > 0:
        result += '.'
        for i in range(decimal_places):
            result += '9'

    return Decimal(result)

No type checks are done because we make the following assumptions:

The results are as follows:

>>> get_max_decimal_number(4, 2)
Decimal('99.99')
>>> get_max_decimal_number(2, 2)
Decimal('0.99')
>>> get_max_decimal_number(1, 0)
Decimal('9')

You can test it out here

My solution right now feels a bit hacky. Is there a better way to do this? Maybe some built in method that I'm not aware of.

Upvotes: 2

Views: 124

Answers (2)

CodeIt
CodeIt

Reputation: 3618

Try this,

def get_max_decimal_number(max_digits, decimal_places):
  return float('9'*(max_digits-decimal_places)+'.'+'9'*decimal_places)

print(get_max_decimal_number(2,2)) # outputs 0.99

print(get_max_decimal_number(4, 2)) # outputs 99.99

print(get_max_decimal_number(1, 0)) # outputs 9.0

See it in action here

You may use Decimal instead of float to type cast the result.

Upvotes: 3

inof
inof

Reputation: 495

from decimal import Decimal

def get_max_decimal_number(max_digits, decimal_places):
    return Decimal('9' * (max_digits - decimal_places) + '.' + '9' * decimal_places)

Upvotes: 0

Related Questions