1

How can I format a floating point number such that I limit the number of decimal places to a fixed length, but do not add padding zeros in the case when the number has less decimal places than asked for?

For printing with fixed precision, I would usually do the following:

print('{:.3f}'.format(123.4567)) # prints 123.457

However for number with less than 3 decimals, it adds padding zeros:

print('{:.3f}'.format(123.4)) # prints 123.400

What I would like is to have the second version keep the argument unchanged:

print('{:.3f}'.other_format(123.4)) # should print 123.4

What is a possible method to have the number printed as in the third example?

Thank you!

8
  • try using g instead of f, although, that might turn it into an exponential. Commented Aug 4, 2022 at 17:48
  • 1
    but honestly, you can also just do something like result = '{:.3f}'.format(123.4) and. if '.' in result: result = result.rstrip("0") which is not pretty but might be more reliable Commented Aug 4, 2022 at 17:50
  • I think you can just use the round function on the number prior to printing it. number = 124.4 number = number.round(1) print(number) output: 124.4 Commented Aug 4, 2022 at 17:51
  • @Mouse the OP is not trying to round though Commented Aug 4, 2022 at 17:51
  • @juanpa.arrivillaga Good point, but if you do print_number = number.round(3) say, won't this always work for printing a number to 3 decimal places, removing zero padding? Granted, it might be very inefficient for the task at hand Commented Aug 4, 2022 at 17:53

2 Answers 2

0

Just do it like this (round will cut additional zeros):

print(round(123.4, 3))
Sign up to request clarification or add additional context in comments.

4 Comments

It's not round cutting additional zeros, it's print.
Indeed for the example I have posted, it works fine, but I would rather not round the numbers.
From docs: Round a number to a given precision in decimal digits. The return value is an integer if ndigits is omitted or None. Otherwise the return value has the same type as the number. ndigits may be negative.
@Polb ah ok, you didn't mention it in question :)
0

It stupid but answers the question

print('{:.3f}'.format(123.4)[:-2]) # should print 123.4

1 Comment

you can't rely on a hard-coded number though

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.