i want to write a function that do something like 1234 -> 1.23k and i cant solve this error function:
def money_unit(money):
money = float(money)
if money >= 1000000000000000000000000:
money = ( format( money , '.2f' ) / 1000000000000000000000000 )
money = str( money ) 'Sa'
elif money >= 1000000000000000000000 :
money = ( format( money , '.2f' ) / 1000000000000000000000 )
money = str( money ) 'Si'
elif money >= 1000000000000000000:
money = ( format( money , '.2f' ) / 1000000000000000000 )
money = str( money ) 'Qa'
elif money >= 1000000000000000:
money = ( format( money , '.2f' ) / 1000000000000000 )
money = str( money ) 'Qi'
elif money >= 1000000000000:
money = ( format( money , '.2f' ) / 1000000000000 )
money = str( money ) 'T'
elif money >= 1000000000:
money = ( format( money , '.2f' ) / 1000000000 )
money = str( money ) 'B'
elif money >= 1000000:
money = ( format( money , '.2f' ) / 1000000 )
money = str( money ) 'M'
elif money >= 1000:
money = str.format( money , "{:. 2f}" ) / 1000
money = str( money ) 'K'
return money
and when i input a nummber with 4 digits or more(when it actualy do something) the error close that error:
Traceback (most recent call last):
File "C:\Users\treed\PycharmProjects\pythonProject1\pythaon - Copy.py", line 91, in <module>
print(money_unit(input()))
File "C:\Users\treed\PycharmProjects\pythonProject1\pythaon - Copy.py", line 78, in money_unit
money = str.format( money , "{:. 2f}" ) / 1000
TypeError: descriptor 'format' for 'str' objects doesn't apply to a 'float' object
Process finished with exit code 1
CodePudding user response:
You are using str.format inappropriately. f-strings are the preferred mechanism for this kind of work.
You can also significantly reduce your runtime code by using a control structure.
Something like this:
CONTROL = [
(1000000000000000000000000, 'Sa'),
(1000000000000000000000, 'Si'),
(1000000000000000000, 'Qa'),
(1000000000000000, 'Qi'),
(1000000000000, 'T'),
(1000000000, 'B'),
(1000000, 'M'),
(1000, 'K')
]
def money_unit(money):
money = float(money)
for m, s in CONTROL:
if money >= m:
return f'{money/m:.2f}{s}'
return f'{money:.2f}'
print(money_unit(1234))
Output:
1.23K
CodePudding user response:
There are better efficient ways of achieving what you are doing. Also you are changing the original parameter passed from integer to string which works but just wanted to point out...but regardless try following
money_str= f"{money/1000:.2f}K"
money_str= f"{money/1000000:.2f}M"
etcc..
CodePudding user response:
I once had to write a function for this as well, to convert numbers to a human readable format. It is a small function and uses the standard math library for its calculations.
from math import log, floor
def human_format(number: float) -> str:
units = ["", "K", "M", "B", "T", "Qi", "Qa", "Si", "Sa"]
k = 1000.0
magnitude = int(floor(log(number, k)))
return "%.2f%s" % (number / k**magnitude, units[magnitude])