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.
To format floats without trailing zeros with Python, we can use the rstrip method. We interpolate x into a string and then call rstrip with 0 and '. ' to remove trailing zeroes from the number strings. Therefore, n is 3.14.
format("%. 2f", 1.23456); This will format the floating point number 1.23456 up-to 2 decimal places, because we have used two after decimal point in formatting instruction %.
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'
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)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With