Ich möchte für eine Ausgabe in ein File meine Rechenergebnisse (floats) immer fix auf 3 Nachkommastellen ausgegeben haben. Das heisst, dass statt 4.2 beispielsweise 4.200 stehen soll. Wie kann ich das erreichen, mit round() gehts logischerweise nicht.
Ich hab folgendes Skript gschrieben. Wie ist das vereinfachbar? Kommt mir zu umständlich vor.
Code: Alles auswählen
# -*- coding: cp1252 -*-
# comma correction function
def comma_cor(float_val, decimals):
corr_val = str(round(float_val,decimals))
corr = corr_val.split('.')[1]
zeros = ''
# unsaubere Lösung
for i in range(len(corr), decimals):
zeros = i * '0'
corr_val = corr_val + zeros
if len(corr_val.split('.')[1]) > decimals:
corr_val = corr_val[0:len(corr_val)-1]
return corr_val
decimals = 3
float_list = [1.2, 3.222, 4.11, 3.22, 3.22234]
for floats in float_list:
print comma_cor(floats, decimals)
Johannes