riscontrano difficoltà a convertire un galleggiante per stringa, nel modo seguente:Convertire float a stringa con taglio a zero decimali afer punto in Python
20.02 --> 20.02
20.016 --> 20.02
20.0 --> 20
Sembra che il formato %g
è la migliore per questo, ma sono ottenendo risultati strani:
In [30]: "%.2g" % 20.03
Out[30]: '20'
In [31]: "%.2g" % 20.1
Out[31]: '20'
In [32]: "%.2g" % 20.3
Out[32]: '20'
In [33]: "%.2g" % 1.2
Out[33]: '1.2'
In [34]: "%.2g" % 1.0
Out[34]: '1'
In [35]: "%.2g" % 2.0
Out[35]: '2'
In [36]: "%.2g" % 2.2
Out[36]: '2.2'
In [37]: "%.2g" % 2.25
Out[37]: '2.2'
In [38]: "%.2g" % 2.26
Out[38]: '2.3'
In [39]: "%.3g" % 2.26
Out[39]: '2.26'
In [40]: "%.3g" % 2.25
Out[40]: '2.25'
In [41]: "%.3g" % 20.02
Out[41]: '20'
In [42]: "%.3g" % 20.016
Out[42]: '20'
In [43]: "%.20g" % 20.016
Out[43]: '20.015999999999998238'
l'unica soluzione che conosco in questo momento sta controllando se il numero è un int
e applicando %d
invece di %f
formattazione - questo è troppo complicato, io pensare.
Qualcuno sa perché le cose di cui sopra stanno scendendo? Come farlo in un modo più semplice?
Grazie.
che Avatar probabilmente non durerà. –
@Jed, sembra che sia durato almeno un anno ormai;) –