-2

I am creating a length calculator and need to format it so it doesn't show 1e-5 from going to mm to km. i have tried '{:.6}'.format() but doesn't seem to work as still outputs it as 1e-5.

Any help on what to do to get rid of this?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Bambii
  • 19
  • 3

1 Answers1

0

Use the f presentation type insteaf of the default (g with a small modification):

'{:.6f}'.format(floating_point_number)

See the Format Specification Mini-Language documentation:

'f'
Fixed point. Displays the number as a fixed-point number. The default precision is 6.

[...]

'g'
General format. For a given precision p >= 1, this rounds the number to p significant digits and then formats the result in either fixed-point format or in scientific notation, depending on its magnitude.

[...]

None
Similar to 'g', except that fixed-point notation, when used, has at least one digit past the decimal point. The default precision is as high as needed to represent the particular value. The overall effect is to match the output of str() as altered by the other format modifiers.

Note that if all you are doing is formatting a float (and not include any other string in your str.format() template), you may as well avoid having to parse the template and use the format() function directly:

format(floating_point_number, '.6f')

Demo:

>>> fp = 1e-5
>>> fp
1e-05
>>> format(fp, '.6f')
'0.000010'
>>> '{:.6f}'.format(fp)
'0.000010'
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • yes this works but it still outputs, say from going to Km to Meters, it will show the answer as 2000.000000. Is there any way to just get it to print 2000 in this situation without the need for all the 0's – Bambii Jun 21 '16 at 07:03
  • See [Formatting floats in Python without superfluous zeros](http://stackoverflow.com/q/2440692); when using `format()` that'd be `format(fp, '.6f').rstrip('0').rstrip('.')`. – Martijn Pieters Jun 21 '16 at 07:07