Skip to content Skip to sidebar Skip to footer

How To Discard Useless Zero Digits From Decimals?

I'm new in Python and I have a problem about the decimal library. Some questions require that all zeros after the decimal point located behind the last non-zero digit must be disca

Solution 1:

Did you try normalize?

Normalize the number by stripping the rightmost trailing zeros and converting any result equal to Decimal('0') to Decimal('0e0').

It should work in your case.

import decimalprint(decimal.Decimal('0.1230000').normalize())
0.123

Solution 2:

A very basic posibility is to work on the str output.

s = '0.1230000'if'.'in s:
    whilelen(s) > 0 and s[-1] == '0':
        s = s[:-1]

Its not very elegant, but it does the job. But this is more work if you need to convert it back to a Decimal instance afterwards.

EDIT: added basic check to only remove zeros after the decimal point.

Post a Comment for "How To Discard Useless Zero Digits From Decimals?"