简体   繁体   中英

Investment calculator - returned number format issue

I've created a function, which returns DataFrame with 3 columns - Year, Principal amount and End balance. It works fine, however the format number of End balance is weird, but I'm not sure, what I've done wrong.

If the input is investment_calculator(15000,7,10) . It returns End balance in correct format:

在此处输入图像描述

However if it exceeds particular amount, eg investment_calculator(15000,10,10) . The format of End balance is different, although nothing's changed:

在此处输入图像描述

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. 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}" .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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