I format the values ​​in a string, it is necessary that only significant digits on the right are saved, and if they are not there at all, the number is inserted into the string as an integer. I.e:

x = 10.0 # Типа флот y = 12.2 '{1:тут_какой-то_хитрый_формат} - {2:такой_же_формат}'.format(x, y) --> '10 12.2' 
  • one
    with light ... - karmadro4

3 answers 3

Then only with your hands:

 print('{0:.1f}'.format(10.0).rstrip('0').rstrip('.')) 

Or expand the functionality of the format:

 from string import Formatter class Fmt(Formatter): def format_field(self, value, spec): if spec[-1] == 'p': spec = '{0}f'.format(spec[:-1]) return super(Fmt, self).format_field(value, spec).rstrip('0').rstrip('.') return super(Fmt, self).format_field(value, spec) fmt = Fmt() print(fmt.format('{0:.1p} - {1:.1p}', 10.0, 10.2)) 

    This is how the% g format works for me for the old formatting method:

     In [47]: "%g" % 19.0 Out[47]: '19' In [48]: "%g" % 19.1 Out[48]: '19.1' In [50]: "%g" % 19.0001 Out[50]: '19.0001' In [51]: "%g" % 19.00001 Out[51]: '19' 

    Using the .n attribute, you can specify the number of significant digits:

     In [56]: "%.8g" % 19.0000001 Out[56]: '19' In [57]: "%.9g" % 19.0000001 Out[57]: '19.0000001' 

    I do not know why it works this way, it seems that the documentation does not say about it.

    • .n - unfortunately not after a comma, but in total. At overflow, g shows in a normal form with + E, which is also not ice ... - myx

    Not quite on the topic, but so far it only comes to mind

     a = 10.0 x = int(a) if a - int(a) == 0.0 else a 

    but since my main C ++ language is confused by checking == 0.0 .

    • one
      Normal check :) Of course you can, somehow, like this: if x == int (x): format_x = int (x) else: format_x = x - Ekkertan
    • I agree, it will be better. - fogbit