Home > Software design >  How can I dynamically decrease by 1 decimal point, regardless of the scale of the number
How can I dynamically decrease by 1 decimal point, regardless of the scale of the number

Time:12-08

Hi I'd like to have some code in Python where 4.16 can go to 4.15 and 416 can go to 415 and 41600 goes go 41599. How would I do this?

CodePudding user response:

Here's one way:

def decrease_by_1(num):
    is_int = isinstance(num, int)
    count = 0
    while num != int(num):
        num *= 10
        count  = 1
    num -= 1
    retval = num / (10 ** count)
    return int(retval) if is_int else retval


print(decrease_by_1(4.16))
print(decrease_by_1(416))
print(decrease_by_1(41600))

Result:

4.15
415
41599

CodePudding user response:

Here is another way. But wondering what you're really trying to do.

Sound's like a real basic question. Maybe you'd run a tutorial first and start getting into it step by step.

from decimal import Decimal

a = 4.16
b = 416
c = 41600

print(type(a))
print(type(b))
print(type(c))

x = Decimal(a) - Decimal(0.01)
print(round(x, 2))
print(b - 1)
print(c - 1)

Result:

<class 'float'>
<class 'int'>
<class 'int'>
4.15
415
41599

CodePudding user response:

Using some strings manipulation would achieve what you need (even if not a numerical solution - and yes, I would really be curious myself what the purpose of this is):

def sub(n):
    ns = str(n)
    i = ns.index(".") if "." in ns else -1
    ns = str(int(ns.replace(".","")) - 1)
    res = ("." if i > -1 else "").join([ns[:i], ns[i:]])
    return float(res) if i > -1 else int(res)

print(sub(4.15))
print(sub(416)) 
print(sub(41600))

OUTPUT

4.14
415
41599

CodePudding user response:

You could convert to a string replacing all digits with zeroes except the last one (which you replace by 1) then use that as a numeric of the same type to subtract the appropriately scaled 1:

def dec1(n):
    zero = str.maketrans("123456789","0"*9)
    return n-type(n)(str(n).translate(zero)[:-1] "1")

Output:

for n in (4.16,416,41600,-2.5):
    print(n,dec1(n))

4.16 4.15
416 415
41600 41599
-2.5 -2.4

Keep in mind that if you intend to use this repeatedly on a number with more than 1 decimal positions, the scale will go up after processing a value ending by 1:

4.22 -> 4.21 -> 4.2 -> 4.1 -> 4.0 -> 3.9

  • Related