Home > Net >  How to print whole number without zeros after decimal point?
How to print whole number without zeros after decimal point?

Time:11-14

I'm trying to print a whole number (such as 39 for example) in the following format: 39. It must not be a str type object like '39.' for example, but a number

e. g. n = 39.0 should be printed like 39.

n = 39.0
#magic stuff with output
39.

I tried using :.nf methods (:.0f apparently -- didn't work), print(float(39.)) or just print(39.) In the first case, it looks like 39, in the second and third 39.0 I also tried float(str(39) '.') and obviously it didn't work

Sorry, if it's a stupid question, I've been trying to solve it for several hours already, still can't find any information.

CodePudding user response:

From Format Specification Mini-Language (emphasis mine):

The '#' option causes the “alternate form” to be used for the conversion. The alternate form is defined differently for different types. This option is only valid for integer, float and complex types. For integers, when binary, octal, or hexadecimal output is used, this option adds the respective prefix '0b', '0o', '0x', or '0X' to the output value. For float and complex the alternate form causes the result of the conversion to always contain a decimal-point character, even if no digits follow it. Normally, a decimal-point character appears in the result of these conversions only if a digit follows it. In addition, for 'g' and 'G' conversions, trailing zeros are not removed from the result.

>>> n=39.0
>>> print(f'{n:#.0f}')
39.
  • Related