-1

I have a dataframe, and I need to add a currency sign to a numeric value in a column, so that the datatype of that column will still remain the same as float type, so i can sum or find mean.

when I add '$' sign to numeric value, all values change their type to string

I tried format, but it convert values to string datatype

Derek O
  • 16,770
  • 4
  • 24
  • 43
Maya
  • 1
  • 1
  • 1
    on stackoverflow, it's a best practice to include the code you've tried in the question, and also a sample of your dataframe so we can reproduce the issue. that being said, what you're asking for doesn't sound possible – when you add a non-numeric symbol, your column becomes a string or object type – Derek O Apr 14 '23 at 17:14
  • Welcome to Stack Overflow. Please checkout the [tour], [ask] and [editing help](https://stackoverflow.com/editing-help). Additionally add the appropriate code in your question as text. See [mre] for more details. – Marcelo Paco Apr 14 '23 at 17:16

1 Answers1

0

You probably don't want to store the value including a dollar sign ($), but rather to prepend or append the dollar sign to the value when you're generating user-facing text.

For instance, you could write code that looks like this:

price = my_function_to_get_a_price()  # price is now a float
print(f"The price is ${price:.2f}")

However, it's possible that when dealing with currency you may encounter a variety of floating point errors. It's therefore often best practice to either store amounts of currency as an int representing cents (so, $1.37 would be 137) or use the decimal library.

See also this answer from Rex Logan.

theo
  • 149
  • 8