[英]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. 鉴于
max_digits
和decimal_places
,该方法将返回最大可能的十进制数。 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: 因为我们做以下假设,所以不进行类型检查:
max_digits
is an integer greater than or equal to 1. max_digits
是大于或等于1的整数。 decimal_places
is an integer greater than or equal to 0, and less than or equal to the max_digits
. decimal_places
是一个大于或等于0且小于或等于max_digits
。 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.
也许一些我不知道的内置方法。
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. 您可以使用Decimal而不是
float
来键入强制转换结果。
from decimal import Decimal
def get_max_decimal_number(max_digits, decimal_places):
return Decimal('9' * (max_digits - decimal_places) + '.' + '9' * decimal_places)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.