Search code examples
pythonstring-formattingpadding

How to format a float with a maximum number of decimal places and without extra zero padding?


I need to do some decimal place formatting in python. Preferably, the floating point value should always show at least a starting 0 and one decimal place. Example:

Input: 0
Output: 0.0

Values with more decimal places should continue to show them, until it gets 4 out. So:

Input: 65.53
Output: 65.53

Input: 40.355435
Output: 40.3554

I know that I can use {0.4f} to get it to print out to four decimal places, but it will pad with unwanted 0s. Is there a formatting code to tell it to print out up to a certain number of decimals, but to leave them blank if there is no data? I believe C# accomplishes this with something like:

floatValue.ToString("0.0###")

Where the # symbols represent a place that can be left blank.


Solution

  • What you're asking for should be addressed by rounding methods like the built-in round function. Then let the float number be naturally displayed with its string representation.

    >>> round(65.53, 4)  # num decimal <= precision, do nothing
    '65.53'
    >>> round(40.355435, 4)  # num decimal > precision, round
    '40.3554'
    >>> round(0, 4)  # note: converts int to float
    '0.0'