31

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.

0

4 Answers 4

37

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'
3
  • ..... Yeah. Yeah, that'd be it. I was looking for formatting because that's how the original code accomplished it, but this is what I want. Guess you could call that a brain-fart.
    – KChaloux
    Commented May 8, 2012 at 20:26
  • 1
    This does not work; round(0.000000001, 4) gives 0.0 Commented Dec 24, 2020 at 23:08
  • 1
    @user5359531 It does work. 0.0000 and 0.0 are equivalent. If you want a string, then you need to use something like format.
    – Akaisteph7
    Commented Nov 14, 2022 at 17:04
9

Sorry, the best I can do:

' {:0.4f}'.format(1./2.).rstrip('0')

Corrected:

ff=1./2.
' {:0.4f}'.format(ff).rstrip('0')+'0'[0:(ff%1==0)]
3
  • You're most of the way there. His C# example would format 1 as '1.0' and yours would format it as '1.'. Commented May 8, 2012 at 19:31
  • float('{:0.4f}'.format(x).rstrip('0')) this should take care of the issue with passing ints too. >>>float('{:0.4f}'.format(1).rstrip('0')) 1.0
    – tapan
    Commented May 8, 2012 at 19:34
  • @tapan: That returns a float, not a string. Commented May 8, 2012 at 19:36
3

From trial and error I think :.15g is what you want:

In: f"{3/4:.15g}"
Out: '0.75'

In f"{355/113:.15g}"
Out: '3.14159292035398'

(while f"{3/4:.15f}" == '0.750000000000000')

1
  • Keep in mind that g specifier may switch to scientific notation for very large or small numbers. For example f"{1/11300:.15g}" results in '8.84955752212389e-05'
    – jodag
    Commented Aug 7, 2022 at 20:06
0
>>> def pad(float, front = 0, end = 4):
    s = '%%%s.%sf' % (front, end) % float
    i = len(s)
    while i > 0 and s[i - 1] == '0':
        i-= 1
    if s[i - 1] == '.' and len(s) > i:
        i+= 1 # for 0.0
    return s[:i] + ' ' * (len(s) - i)

>>> pad(0, 3, 4)
'0.0   '
>>> pad(65.53, 3, 4)
'65.53  '
>>> pad(40.355435, 3, 4)
'40.3554'
4
  • You're most of the way there. His C# example would format 1.0 as '1.0' and yours would format it as '1.'. Commented May 8, 2012 at 19:52
  • Interesting solution. It works for whole numbers, but trying to pass in a value of say, 2.5 always seems to return None. I'll poke around a bit more. I was kind of hoping there was something built into the format function to handle this.
    – KChaloux
    Commented May 8, 2012 at 20:00
  • Oh sorry - i copied it from my pyshell and it looked good with tabs but it corrupted the identation.
    – User
    Commented May 8, 2012 at 20:02
  • Seems to be working now. I'll give this the answer unless somebody can come up with a solution I that suits me better.
    – KChaloux
    Commented May 8, 2012 at 20:13

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.