簡體   English   中英

投資計算器 - 返回數字格式問題

[英]Investment calculator - returned number format issue

我創建了一個 function,它返回 DataFrame 3 列 - 年、本金和期末余額。 它工作正常,但是 End balance 的格式編號很奇怪,但我不確定,我做錯了什么。

如果輸入是investment_calculator(15000,7,10) 它以正確的格式返回結束余額:

在此處輸入圖像描述

但是,如果它超過特定金額,例如investment_calculator(15000,10,10) End balance 的格式有所不同,但沒有任何變化:

在此處輸入圖像描述

Function:

def investment_calculator(amount,years,interest):
    """
    Investment calculator calculates returned amount.

    Args:
        amount: monthly invested amount
        years: number of years
        interest: average yearly interest

    Returns:
        DataFrame
    """
    col_names = ['Year', 'Principal', 'End balance']
    df = pd.DataFrame(columns = col_names)

    i = 1
    while i <= years:
        invested_amount = (amount * 12) * i
        year = datetime.datetime.now().year + (i - 1)
        
        
        if i == 1:
            investment = (amount * 12) * (1 + (interest / 100))
            new_row = {'Year':year, 'Principal':invested_amount, 'End balance':investment}
            df = df.append(new_row, ignore_index=True)
        else:
            investment = (df.iloc[-1,2] + (amount * 12)) * (1 + (interest / 100))
            new_row = {'Year':year, 'Principal':invested_amount, 'End balance':investment}
            df = df.append(new_row, ignore_index=True)
            
        i += 1
        
    return df

有什么想法,請問有什么問題嗎?

顯然,當數字足夠大時, pandas切換到科學數字表示法。 您的代碼不包含實際打印。 當您打印結果時,將它們格式化為合適的格式,可能使用 f-strings: f"{df['End Balance']:.2f}"

我相信您知道您的值只是使用科學計數法顯示的。 如果它打擾您,您可以設置不同的默認格式,例如:

pd.options.display.float_format = '{:.2f}'.format

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM