Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incrementing to the last decimal in python

I want to write function in python when given float or string for example 0.003214 to return me 0.003215, but if I give it 0.00321 to return 0.003211, it will apply on other floats also like 0.0000324 -> 0.00003241. What is wrong with my solution and how do I fix it?

def add_one_at_last_digit(v):
    after_comma = Decimal(v).as_tuple()[-1]*-1
    add = Decimal(1) / Decimal(10**after_comma)
    return Decimal(v) + add
like image 549
Giorgi Samkharadze Avatar asked Oct 16 '25 04:10

Giorgi Samkharadze


1 Answers

Here is a working solution

from decimal import Decimal

def add_one_at_last_digit(v: float | str) -> float:
    d = Decimal(str(v))
    
    decimal_places = abs(d.as_tuple().exponent)
    
    add = Decimal(f"1e-{decimal_places}")
    
    result = (d + add).quantize(Decimal(f"1e-{decimal_places}"))
    
    return float(result)

The key ideas are:

  • d = Decimal(str(v)) gives the a Decimal object with the exact number of decimal places. The string conversion does the trick here. For example
>>> Decimal(213.4)
Decimal('213.400000000000005684341886080801486968994140625')
>>> Decimal("213.4")
Decimal('213.4')

You did not do this in your solution which is why your after_comma is wrong.

  • abs(d.as_tuple().exponent) gives the exact number of decimal places.
  • (d + add).quantize(Decimal(f"1e-{decimal_places}")) again quantizes it to remove imprecision.
like image 185
Sachin Hosmani Avatar answered Oct 17 '25 18:10

Sachin Hosmani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!