Seite 1 von 1

Problem mit Nachkommastellen

Verfasst: Montag 17. Juli 2006, 11:37
von keboo
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

Verfasst: Montag 17. Juli 2006, 11:55
von Rebecca

Code: Alles auswählen

>>> print "%.3f" % 4.1
4.100
>>> print "%.3f" % 4.11234
4.112
>>> 

gelöst

Verfasst: Montag 17. Juli 2006, 11:58
von keboo
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