0

I want to print the length of a float number without trailing zeros using python. examples:

0.001000 >>> I want to get length=5

0.000100 >>> I want to get length=6

0.010000 >>> I want to get length=4

any suggestions?

2 Answers 2

0

Converting a float to a str will automatically remove tailing zeros:

numbers = [0.0010000, 0.00000000100, 0.010000]

for number in numbers:
    number = '{0:.16f}'.format(number).rstrip("0")
    print(f"Converted to String: {str(number)} - Length: {len(str(number))}")

Results:

Converted to String: 0.001 - Length: 5
Converted to String: 0.000000001 - Length: 11
Converted to String: 0.01 - Length: 4
Sign up to request clarification or add additional context in comments.

1 Comment

for numbers with more than 4 zeros, it shows '1e-05' Example: (str(float(0.00001))) >>> '1e-05' (str(float(0.000001))) >>> '1e-06' and then it will calculate the length wrong
0

Try with this:

inp = '0.00100'
len(str(float(inp)))

Output:

This gives the length as 5

All the trailing zeroes will be removed.

1 Comment

for numbers with more than 4 zeros, it shows '1e-05' Example: (str(float(0.00001))) >>> '1e-05' (str(float(0.000001))) >>> '1e-06' and then it will calculate the length wrong

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.