I'm working on a script that needs to output numbers in a precision determined by length and not just decimal places. Let's say I want a max of 7 decimals but whole numbers above 7 digits are ok although they can't have decimals if the total amount of digits is 7 or higher.
So the rules are:
- If a float has more than 7 digits of whole numbers, it loses it's decimals
- If a float has less than 7 digits of whole numbers, it gets a length of 7 total digits including decimals
- If a floats has no digits of whole numbers, it keeps 7 decimals
For example:
a = 10000.02
b = 1.000002
c = 100000000000
are all correct.
How do I handle numbers (all float
) in this format?
For example:
d = 892432589.54680
e = 382.39810758264057251
f = 452545871.1643548
g = 10254.968743541742
h = 165783438364325.126
I was thinking about something along the lines of:
length_of_number = len(str(x))
if length_of_number > 7:
x.round(0)
else:
x.round(7 - length_of_number)
but then I get in trouble with situations like
x= 0.5313231568943218748
because the whole float
is longer than 7 digits.
What to do?
Edit for asked examples:
12345678 is ok
1234567.1 is ok (but 1234567.12 not)
1.12345678 would become 1.123456