简体   繁体   English

投资计算器 - 返回数字格式问题

[英]Investment calculator - returned number format issue

I've created a function, which returns DataFrame with 3 columns - Year, Principal amount and End balance.我创建了一个 function,它返回 DataFrame 3 列 - 年、本金和期末余额。 It works fine, however the format number of End balance is weird, but I'm not sure, what I've done wrong.它工作正常,但是 End balance 的格式编号很奇怪,但我不确定,我做错了什么。

If the input is investment_calculator(15000,7,10) .如果输入是investment_calculator(15000,7,10) It returns End balance in correct format:它以正确的格式返回结束余额:

在此处输入图像描述

However if it exceeds particular amount, eg investment_calculator(15000,10,10) .但是,如果它超过特定金额,例如investment_calculator(15000,10,10) The format of End balance is different, although nothing's changed: End balance 的格式有所不同,但没有任何变化:

在此处输入图像描述

Function: 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

Any ideas, what's wrong, please?有什么想法,请问有什么问题吗?

Apparently pandas switches to scientific number notation when the numbers are sufficiently large.显然,当数字足够大时, pandas切换到科学数字表示法。 Your code does not contain the actual printing.您的代码不包含实际打印。 When you print the results, format them as suitable, possibly by using f-strings: f"{df['End Balance']:.2f}" .当您打印结果时,将它们格式化为合适的格式,可能使用 f-strings: f"{df['End Balance']:.2f}"

I am sure you know your values are simply displayed using scientific notation.我相信您知道您的值只是使用科学计数法显示的。 If its bother you, you can set a different default format, for instance:如果它打扰您,您可以设置不同的默认格式,例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM