0

I want to do operations like

500.55%10 and get a value of 0.55 in return.

But instead Python sometimes returns 0.5500000000000114 for example (which in terms of magnitude is basically the same), I'm guessing this is because of the numerical way these calculations are done.

When I input a value like 500.55 I want it to be seen as 500.55000000000000.... with an infinite amount of zeros. So basically I want to get rid of ...00114 at the end.

print(500.55%10)
0.5500000000000114

Thanks.

  • 1
    Try reading more about the built-in [`decimal` module](https://docs.python.org/3/library/decimal.html#quick-start-tutorial) – crissal Aug 14 '22 at 16:00

3 Answers3

0

you can use the round function to round. Alternatively you need to use the decimal module which handles extra decimals in the way that you ask...

here are both methods:

import decimal

# normal way
print('normal way:', 500.55%10)   

# do some rounding
print('rounding:', round(500.55%10, 10) )

# use the decimal
decimal.getcontext().prec = 10
print('decimal module:',  decimal.Decimal(500.55)%decimal.Decimal(10))

result:

normal way: 0.5500000000000114
rounding: 0.55
decimal module: 0.5500000000
D.L
  • 4,339
  • 5
  • 22
  • 45
0

Try the decimal module:

>>> from decimal import Decimal
>>> float(Decimal('500.55') % 10)
0.55

Documentation here.

The Thonnu
  • 3,578
  • 2
  • 8
  • 30
0

you can use the built-in decimal module and their decimal.Decimal object.

decimal.Decimal(value='0', context=None)

from the documentation:

Construct a new Decimal object based from value.

value can be an integer, string, tuple, float, or another Decimal object. If no value is given, returns Decimal('0'). If value is a string, it should conform to the decimal numeric string syntax after leading and trailing whitespace characters, as well as underscores throughout, are removed

Example implementation:

>>> import decimal
>>> float(decimal.Decimal('500.55') % 10)
0.55
XxJames07-
  • 1,833
  • 1
  • 4
  • 17