user12379570
user12379570

Reputation: 9

place a decimal point function in python

I am looking to write a function in python that places a decimal point into some string.

for example if the string I give is '12355' and then I put the point place in 2 the output should skip the first two numbers and show '12.355'

please help, thank you

Upvotes: 0

Views: 95

Answers (4)

PieCot
PieCot

Reputation: 3639

def add_decimal_point(s, n):
    return f'{s[:n]}.{s[n:]}' if 0 < n < len(s) else s

add_decimal_point("23567", 2)

23.567

If n is greater or equal to the length of the string or if it is negative, the original string is returned:

add_decimal_point("23567", 10)

23567

Upvotes: 1

godot
godot

Reputation: 3545

Or you can treat this string mathematically as a number:

s = "12355"
n = float(s)
length = len(s)

place = 2
power = length - place

print(n / (10 ** power))

lets separate logic into the function:

def decimal_point(s, place):
        n = float(s)
        length = len(s)
    
    
        power = length - place
    
        return n / (10 ** power)

Upvotes: 0

damon
damon

Reputation: 15128

You can use string indexing, as if it were a list:

def insert_decimal_point(number, position):
    return number[:position] + "." + number[position:]

Upvotes: 2

Technology Dev
Technology Dev

Reputation: 68

Here

place = 3
number = "12345"
result = number[:place] + "." + number[place:]
print(result)

The result will have the decimal point 3 characters from the first one. When I run it the output is

123.45

If you were to do a function, then

def insert_decimal(position,number):
  return number[:position] + "." + number[position:]

Upvotes: 2

Related Questions