3

I don't know if i am asking my question right, but i want to know if its possible for me to multiply two numbers, and place a decimal depending on the length of the number?

I am currently doing something like this

def multiply(input1, input1):
    num = (input1 * input1)
    if len(str(num)) == 4 and str(num).isdigit():
        print(num)

    return num

multiply(225, 10)

Instead of returning something like 2250, i will like to return something like 2.25k. Is there an inbuilt function in python to achieve this?

Thank you.

Now i am currently doing something like this

from __future__ import division
    def multiply(string1, string2):
        num = (string1 * string2)
        if len(str(num)) == 4 and str(num).isdigit():
            num = format(num/1000, '.2f')
            print(num + "k")
        elif len(str(num)) == 5 and str(num).isdigit():
            num = format(num/1000, '.1f')
            print(num + "k")
        return num
multiply(225, 10)

How efficient is this?

PythonRookie
  • 301
  • 1
  • 5
  • 20
  • If you are looking for an inbuilt function, you can try `"{:0.3e}".format(2250)` or any `num` in place of `2250`. Not exactly your requirement, but might be useful – nikpod Jun 21 '17 at 04:13
  • Possible duplicate of [Python library to convert between SI unit prefixes](https://stackoverflow.com/questions/10969759/python-library-to-convert-between-si-unit-prefixes) – BrockLee Jun 21 '17 at 04:14

1 Answers1

1

If you want a simple example of how this can be done, take a look,

def m(a, b):
     num = float(a * b)

     if num / 1000 > 1:
         return str(num/1000) + "k"
     else:
         return num

>>> m(225, 10)
'2.25k'
zaidfazil
  • 9,017
  • 2
  • 24
  • 47