Problem mit Nachkommastellen

Wenn du dir nicht sicher bist, in welchem der anderen Foren du die Frage stellen sollst, dann bist du hier im Forum für allgemeine Fragen sicher richtig.
Antworten
keboo
User
Beiträge: 132
Registriert: Sonntag 19. Februar 2006, 14:03

Hallo Leute!
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)

Danke,

Johannes
Benutzeravatar
Rebecca
User
Beiträge: 1662
Registriert: Freitag 3. Februar 2006, 12:28
Wohnort: DN, Heimat: HB
Kontaktdaten:

Code: Alles auswählen

>>> print "%.3f" % 4.1
4.100
>>> print "%.3f" % 4.11234
4.112
>>> 
keboo
User
Beiträge: 132
Registriert: Sonntag 19. Februar 2006, 14:03

hi!

die while schleife gibts ja auch noch ;)

Code: Alles auswählen


# -*- coding: cp1252 -*-
# comma correction function

# float values, whic 

def comma_cor(float_val, decimals):

    corr_val = str(round(float_val,decimals))

    corr = corr_val.split('.')[1]

    x =  len(corr)

    while x < decimals:
        corr_val = corr_val + '0'
        x = x+1
    
    return corr_val

danke trotzdem,

johannes
Antworten