0

I have an output that is a string, such as: price: "0.00007784"

I'd like to convert that string to a number so as I can perform arithmetic on it (add 10% to it, for example). However, I try: convertedPrice = int(float(number)) and I get 0 as the result. I need the whole string converted to a number, as it is and not in scientific form.

What am I doing wrong?

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
  • 1
    Why are you converting it to an integer when it's a tiny fraction? – Barmar Jan 03 '22 at 17:51
  • `int` means `integer`, as in whole number, so it will 'throw away' everything after the decimal place. In terms of scientific notation, operate on it as a `float` then use string formatting to display it when you finally output results. – match Jan 03 '22 at 17:51
  • 2
    Just use `float()` not `int()` – Barmar Jan 03 '22 at 17:52
  • 0.00007784 is pretty low cost... –  Jan 03 '22 at 17:52
  • 1
    In your own words, what is an integer? Can `0.00007784` be represented as an integer? In your own words, where you have `int(float(number))`, what do you think the `float` part means? What do you think the `int` part means? – Karl Knechtel Jan 03 '22 at 17:52
  • 1
    I’m voting to close this question because it appears not to be a question about programming, but a question about definitions. It only makes sense to ask this question if someone thinks that "integer" and "number" mean the same thing, which they do not. – Karl Knechtel Jan 03 '22 at 17:53
  • Scientific notation is an input/output format, it's not part of the value of the number. You can use formatting operators to control whether this format is used. – Barmar Jan 03 '22 at 17:53
  • As mentioned, the scientific notation is just a matter of ***representing*** the number, not how it is saved in memory. So while `print(float("0.00007784"))` will give `7.784e-05`, you can control for example by doing `print(format(float("0.00007784"), 'f'))` which will give `0.000078` – Tomerikoo Jan 03 '22 at 17:56
  • Does this answer your question? [How to suppress scientific notation when printing float values?](https://stackoverflow.com/q/658763/6045800) – Tomerikoo Jan 03 '22 at 17:57

1 Answers1

1

The reason that the string is converted to a whole number is because you use the int function to convert it to an integer.

When you print the float value you may get the scientific notation, but that does not mean it is stored in scientific notation, this is only the way it represented when converted back to a string. This question’s answer explain how this can be avoided.

An alternative would be to use Decimal if you want it to be very specifically stored in decimal notation, and the cost of increased computation.

  • In fact, a floating-point number is always stored in scientific notation (though with a power of 2). –  Jan 03 '22 at 18:04