0

I'm calculating FX rates in Python.

Doing a really simple calculation of rate = currency_1_rate/currency_2_rate (where rates for both currencies are just a decimal number), which is returning a rate in scientific notation with a lower case 'e'.

For example IDR to USD rate is being returned as: 6.87758e-05

Is there a way to get python to output these numbers/rates using a capital E for the scientific notation instead? There are processes further down the line that might not accept this lower case 'e' notation.

I am doing a pandas to_csv with these rates, so ideally don't to be converting to a string then back to a number.

Jerry12345678
  • 251
  • 1
  • 2
  • 6
  • 2
    If `val` is the value you want to print, you could do this: `print(f"{val:E}")` which works as a format specifier. I encourage you to learn more about these format specifiers, as they make tasks ridiculously simple later on. – Robo Mop Jul 01 '21 at 10:51
  • 2
    Unrelatedly: You probably don't want to use floating point numbers for currency exchange rates. – gspr Jul 01 '21 at 10:59
  • 1
    @gspr You can probably drop the "probably". – chepner Jul 01 '21 at 11:38
  • I converted the input table type to be float: fx_rates = fx_rates.astype({2:'float'}) – Jerry12345678 Jul 01 '21 at 11:43
  • @Jerry12345678: That's a bad idea. https://stackoverflow.com/q/3730019/453616 – gspr Jul 01 '21 at 11:48
  • How can I convert my table/DF into type Decimal? Or would I go float and the convert it to decimal? – Jerry12345678 Jul 01 '21 at 12:00

1 Answers1

0

When using .to_csv you can supply the float_format parameter. You can supply with with the E argument, specifing to use scientific notation with capital E.

df.to_csv("path/to/file.csv", float_format="E")

For further reading, see Format Specification Mini Language

tituszban
  • 4,797
  • 2
  • 19
  • 30
  • Forgot to mention that I need to write out this number to a CSV file and want to retain the number and not convert to a string and back to a number. – Jerry12345678 Jul 01 '21 at 11:33
  • Right. That's quite a crucial detail, you should include in your question! – tituszban Jul 01 '21 at 11:34
  • Updated my answer to be in relation to `to_csv` – tituszban Jul 01 '21 at 11:40
  • The above float_format="E" didn't seem to work. So I wrote a really simple bit of code to check why this wasn't working. I get "TypeError: not all arguments converted during string formatting" - any ideas why? – Jerry12345678 Jul 14 '21 at 09:25
  • import os import pandas as pd import numpy as np test = pd.DataFrame(np.array([[1.1111],[2.2222],[3.3333]])) cwd = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__))) test = test.astype('float') test.to_csv(cwd+'\\'+ 'test', index=False, float_format='E') – Jerry12345678 Jul 14 '21 at 09:25