Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python increment float by smallest step possible predetermined by its number of decimals

Tags:

I've been searching around for hours and I can't find a simple way of accomplishing the following.

Value 1 = 0.00531
Value 2 = 0.051959
Value 3 = 0.0067123

I want to increment each value by its smallest decimal point (however, the number must maintain the exact number of decimal points as it started with and the number of decimals varies with each value, hence my trouble).

Value 1 should be: 0.00532
Value 2 should be: 0.051960
Value 3 should be: 0.0067124

Does anyone know of a simple way of accomplishing the above in a function that can still handle any number of decimals?

Thanks.

like image 388
gloomyfit Avatar asked Dec 16 '17 19:12

gloomyfit


1 Answers

Have you looked at the standard module decimal?

It circumvents the floating point behaviour.

Just to illustrate what can be done.

import decimal
my_number = '0.00531'
mnd = decimal.Decimal(my_number)
print(mnd)
mnt = mnd.as_tuple()
print(mnt)
mnt_digit_new = mnt.digits[:-1] + (mnt.digits[-1]+1,)
dec_incr = decimal.DecimalTuple(mnt.sign, mnt_digit_new, mnt.exponent)
print(dec_incr)
incremented = decimal.Decimal(dec_incr)
print(incremented)

prints

0.00531
DecimalTuple(sign=0, digits=(5, 3, 1), exponent=-5)
DecimalTuple(sign=0, digits=(5, 3, 2), exponent=-5)
0.00532

or a full version (after edit also carries any digit, so it also works on '0.199')...

from decimal import Decimal, getcontext

def add_one_at_last_digit(input_string):
    dec = Decimal(input_string)
    getcontext().prec = len(dec.as_tuple().digits)
    return dec.next_plus()

for i in ('0.00531', '0.051959', '0.0067123', '1', '0.05199'):
    print(add_one_at_last_digit(i))

that prints

0.00532
0.051960
0.0067124
2
0.05200
like image 77
ahed87 Avatar answered Sep 23 '22 12:09

ahed87