Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 986
KChaloux Avatar asked May 08 '12 18:05

KChaloux


People also ask

How do I print float without trailing zeros?

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.

How do you keep a float up to 2 decimal places?

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 %.


2 Answers

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' 
like image 170
Zeugma Avatar answered Oct 08 '22 08:10

Zeugma


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)] 
like image 42
f p Avatar answered Oct 08 '22 08:10

f p