How to round a number

Is it possible to round a number to the amount of digit it has.

import math

a = 984.59

x = round(a - math.floor(a) , 2)


In this code i have to say how man digits it has to round. But let’s say i want the code to give me the fractal of 984.59201 which would be 0.59201 without to change anything else. Is there a funtcion to do this.

Possibly, you could use the divmod() function in some way:

x = 984.59201

n, r = divmod(x, 1)
print(n, r)
984.0 0.5920099999999593

… or rather the output from said, least ways.

To add…

If you wanted a floating point number with the same number of digits as the input:

x = 984.59201

_, dp = str(x).split('.')

n, r = divmod(x, 1)

xr = float(f"{r:.{len(dp)}f}")


… although I’d guess that there could be a more concise way to do this, but without using any dependencies, that’s how I would do it and I’d have that coded into a function.

Thinking some more about this, there’s a far simpler way:

x = 984.59201

x1, x2 = str(x).split('.')

output = float('.' + x2)


Hacking the string rep is not required.

You can ask for the formatting of the float to limit the precision.

print(‘%.2f’ % float_value)

Indeed, but my approach was on the assumption that the ‘number’ was needed in a particular format, rather than to simply format the ‘displayed number’, but I could be wrong.

Either use float functions to limit the precision or format at limited precision.
Going via strings seem unnecessary.

That’s simply the modulo operator:

In [17]: 984.59201 % 1
Out[17]: 0.5920099999999593

works for values other than 1, too:

In [18]: 984.59201 % 10
Out[18]: 4.592009999999959

In [19]: 984.59201 % .1
Out[19]: 0.09200999999990464

or you can do this:

In [24]: x - math.floor(x)
Out[24]: 0.5920099999999593


In [25]: x - int(x)
Out[25]: 0.5920099999999593