place a decimal point function in python - 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

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:]

You can use string indexing, as if it were a list:
def insert_decimal_point(number, position):
return number[:position] + "." + number[position:]

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

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)

Related

Python removing first 3 digits in a number

Hopefully a simple one, I have a number, say 1234567.890 this number could be anything but will be this length.
How do I truncate the first 3 numbers so it turns into 4567.890?
This could be any number so subtracting 123000 will not work.
I'm working with map data in UTM coordinates (but that should not matter)
Example
x = 580992.528
y = 4275267.719
For x, I want 992.528
For y, I want 267.719
Note: y has an extra digit to the left of the decimal so 4 need removing
You can use slices for this:
x = 1234567.890
# This is still a float
x = float(str(x)[3:])
print(x)
Outputs:
4567.89
As [3:] gets the starts the index at 3 and continues to the end of the string
Update after your edit
The simplest way is to use Decimal:
from decimal import Decimal
def fmod(v, m=1000, /):
return float(Decimal(str(v)) % m)
print(fmod(x))
print(fmod(y))
Output
992.528
267.719
If you don't use string, you will have some problems with floating point in Python.
Demo:
n = 1234567.890
i = 0
while True:
m = int(n // 10**i)
if m < 1000:
break
i += 1
r = n % 10**i
Output:
>>> r
4567.889999999898
>>> round(r, 3)
4567.89
Same with Decimal from decimal module:
from decimal import Decimal
n = 1234567.890
n = Decimal(str(n))
i = 0
while True:
m = int(n // 10**i)
if m < 1000:
break
i += 1
r = n % 10**i
Output:
>>> r
Decimal('4567.89')
>>> float(r)
4567.89
This approach simply implements your idea.
int_len is the length of the integer part that we keep
sub is the rounded value that we will subtract the original float by
Code
Here is the code that implements your idea.
import math
def trim(n, digits):
int_len = len(str(int(n))) - digits # length of 4567
sub = math.floor(n / 10 **int_len) * 10**int_len
print(n - sub)
But as Kelly Bundy has pointed out, you can use modulo operation to avoid the complicated process of finding the subtrahend.
def trim(n, digits):
int_len = len(str(int(n))) - digits # length of 4567
print(n % 10**int_len)
Output
The floating point thing is a bit cursed and you may want to take Corralien's answer as an alternative.
>>> n = 1234567.890
>>> trim(n, 3)
4567.889999999898
def get_slice(number, split_n):
return number - (number // 10**split_n) * 10**split_n

Python problem creating recursion function

I'm trying to create a function that
The input of it will be a digit.
And the length of the wanted result
The output will be the digit in the length of user input
For example doMul(3,6) will output: 333333.
Now I tried to do this:
def doMul(digit, count=1):
if count == 0:
return 1
return digit + digit * (10 ** doMul(digit, count - 1))
But it doesn't seem to work.
And I can't figure out why.
Worth mentioning I don't want to use any strings.
y ** x is actually y in power of x, not multiplication. You should remove it and return digit rather than 1
def doMul(digit, count=1):
if count == 1:
return digit
return digit + 10 * doMul(digit, count - 1)
def doMul(n, m):
"Return the decimal number that is nnn... m times."
return n * ((10**m)-1) // 9
The reason this works is that M copies of N is simply M copies of 1, multiplied by N. And since (10 ** M) - 1 is the same as doMul(9, m), we can easily generate our base number.
If you absolutely need a recursive solution:
def doMul(n, m):
if m <= 1:
return n
return n + 10 * doMul(n, m-1)
This does essentially the same, compute one digit less than we want, multiply it by 10, then add the digit we want.
Does this work for you?
def doMul(digit, count=1):
if count == 1:
return digit
return str(digit) + str(doMul(digit, count-1))
print(doMul(3, 6))

How to show exactly 4 numbers after decimal point without rounding in Python?

I want to calculate square root of numbers and print them with exactly 4 numbers after decimal point without rounding.
This code rounds the numbers
num="%.4f" % num
and this one doesn't show 1.0000 or numbers like this.
num=math.floor(num * 10000)/10000
Here is an option if you wish printing / just showing the 4 numbers after decimal point:
num = 0.553252
'{:.4f}'.format(num)
You can find more information on presenting strings / values here -
https://pyformat.info/#number
Try this:
>>> num = 5.12129
>>> num = f'{num:.5f}'[:-1]
>>> num
'5.1212'
You could convert the number to a string, then use string manipulation:
def numberWithoutRounding(num, precision=4):
[beforeDecimal, afterDecimal] = str(num).split('.')
return beforeDecimal + '.' + afterDecimal[0:precision]
>>> numberWithoutRounding(1.43219)
'1.4321'
Move the significant digits to the left of the decimal point, truncate it with ‘int’ and them move them back.
num = float (int (num * 10000) / 10000)
print (num)
You can convert them into string. Here's a way -
num = str(0.5532523).split('.')
ans = '%s.%s' % (num[0], num[1][:4])
print(ans)
import math
tedad=int(input())
adadlist=[]
rishe=[]
for i in range(0,tedad):
adadlist.append(int(input()))
n='%.4f'%float(int(math.sqrt(adadlist[i])*10000)/10000)
rishe.append(n)
for x in range(0,len(rishe)):
print(rishe[x])
import math
list = []
n = int(input())
for i in range(n):
digits = float(input())
x = math.sqrt(digits)
formula = '{:.4f}'.format(float(int(x * 10000) / 10000))
list.append(formula)
for v in list:
print(v)
>>> k = 4.35889321
>>> x,y = map(str,str(k).split("."))
>>> print(x+"."+(y[:4]))
4.3588

python3 calculate N digits of PI python cut the long number

i need to write a script that get input from client of an number and i need to print back the PI number until client number
for example: client number is 52 --> 3.14159265358979323846264338327950288419716939937510
so far i write this:
sum = 0
for i in range(1, 1001):
sum += ((-1)**(i+1))*4 / ((i + i)*(i + i + 1)*(i + i + 2))
print(sum)
the issue is that python showing to me only the 17 decimals digits, and i expect to see the 1000 decimal digits.
there is a way to showing all the decimal digits based on the inputed range?
it's for school task, so i need to write is as simple as it can be.
I do not think it is possible to get a a float value with a 1000point precision.
Check https://stackoverflow.com/a/54967370/11152011 to calculate pi up to n-precision
You can then use the "decimal" library to use the string as a number.
The calculation of pi was taken from the above link.
import decimal
DIGITS = 1000
def pi_digits(x):
k,a,b,a1,b1 = 2,4,1,12,4
while x > 0:
p,q,k = k * k, 2 * k + 1, k + 1
a,b,a1,b1 = a1, b1, p*a + q*a1, p*b + q*b1
d,d1 = a/b, a1/b1
while d == d1 and x > 0:
yield int(d)
x -= 1
a,a1 = 10*(a % b), 10*(a1 % b1)
d,d1 = a/b, a1/b1
digits = [str(n) for n in list(pi_digits(DIGITS))]
str_pi='{}.{}'.format(digits.pop(0), "".join(digits)
context = decimal.Context(prec=100)
decimal.setcontext(context)
pi = decimal.Decimal(str_pi)
print(pi+5)
print(pi*20)
I don't know how accurate is this but for a small class assignment i guess do the following:
num=52 #input
pi=22/7;
print('{:.{}f}'.format(pi, num))

How to added up a variable with multiple values together in Python Recursion Function?

So I was studying recursion function online. And the one question asks me to write a function to add up a number's digits together. For example (1023) -> 1 + 0 + 2 + 3 = 6. I used % and // get get rid of a digit each time. However, I don't know how to add them up together. The closest I can get is to print out each digit. Can anyone help me solve it or give me a hint please?
def digitalSum(n):
if n < 10:
sum_total = n
print(sum_total)
else:
sum_total = n % 10
digitalSum((n - (n % 10))//10)
print(sum_total)
digitalSum(1213)
Your function should return the current digit plus the sum of the rest of the digits:
def digitalSum(n):
if n < 10: return n
return n % 10 + digitalSum(n // 10)
print digitalSum(1213)
For completeness, you can also handle negative numbers:
def digitalSum(n):
if n < 0: sign = -1
else: sign = 1
n = abs(n)
if n < 10: return n
return sign * (n % 10 + digitalSum(n // 10))
print digitalSum(1213)
A correct version of your function is as follows:
from math import log10
def sum_digits(n, i=None):
if i is None:
i = int(log10(abs(n)))
e = float(10**i)
a, b = (n / e), (abs(n) % e)
if i == 0:
return int(a)
else:
return int(a) + sum_digits(b, (i - 1))
print sum_digits(1234)
print sum_digits(-1234)
Example:
$ python -i foo.py
10
8
>>>
Updated: Updated to properly (IHMO) cope with negative numbers. e.g: -1234 == -1 + 2 + 3 + 4 == 8
NB: Whilst this answer has been accepted (Thank you) I really think that perreal's answer should have been accepted for simplicity and clarity.
Also note: that whilst my solution handles negative numbers and summing their respective digits, perreal clearly points out in our comments that there are ate least three different ways to interpret the summing of digits of a negative number.

Categories