0

I have a dataframe where one of the columns deals with currency displayed in Euros. Due to the rounding issues I want to use the DECIMAL module to have precise arithmetic outcomes.

  • Python command: 0.1 + 0.2 == 0.3 is FALSE
  • Decimal module: Decimal('0.1')+Decimal('0.2') == Decimal('0.3') is TRUE (This is the scenario I am looking for)

JUPYTER NOTEBOOK

d = {'name': ["A", "B", "C"], 'amount': [0.1, 0.2, 0.3]}
df = pd.DataFrame(data=d)
print("Original")
print(df)
print("Original_Test")
print(df['amount'][0]+df['amount'][1]==df['amount'][2])

for col in df:
    if "amount" in col or "eur" in col:
        df[col] = list(df[col])
        df[col] = [Decimal(str(round(i,2))) for i in df[col]]
print("Decimal Layout")
print(df)
print("Decimal Layout_Test")
print(df['amount'][0]+df['amount'][1]==df['amount'][2])

When the above code is run into Jupyter Notebook, the output is correct:

Jupyter Notebook

STREAMLIT

d = {'name': ["A", "B", "C"], 'amount': [0.1, 0.2, 0.3]}
df = pd.DataFrame(data=d)
st.write(df)
for col in df:
    if "amount" in col or "eur" in col:
        df[col] = list(df[col])
        df[col] = [Decimal(str(round(i,2))) for i in df[col]]
st.write(df)
st.write(df['amount'][0]+df['amount'][1]==df['amount'][2])

The same code is then adapted to Streamlit and run. Even thought the output is listed as TRUE the amount column is displayed incorrectly as [1, 2, 3] instead of [0.1, 0.2, 0.3]

Streamlit Output

  • Refrain from showing your dataframe as an image. Your question needs a minimal reproducible example consisting of sample input, expected output, actual output, and only the relevant code necessary to reproduce the problem. See [How to make good reproducible pandas examples](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples) for best practices related to Pandas questions. – itprorh66 Jan 23 '23 at 15:47

1 Answers1

0

This has to do with streamlit and the following is what you can do using df.style.format() method to reset the decimal points when writing the dataframe:

st.write(df.style.format({'amount': '{:.1f}'}))
Jamiu S.
  • 5,257
  • 5
  • 12
  • 34