Hello,
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)
print(x)
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)
output
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}")
print(xr)
output
0.59201
… 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:
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.