1

That's a bit difficult to write in an easy-to-understand title...

When I run float.Parse() on "12E2" or "12e2" it returns 1200 (12*10^2) rather than 144 (12^2). This happens with any number, not just this one case.

Edit: Yes, I know 12E2 is not supposed to give 12^2. I’m asking how you are meant to do it.

What notation would be required to have it return a regular exponent (eg. 12^2)?

I've tried using ^, which throws an error, but I can't seem to tell from the docs what notation is supposed to be used for regular exponents.

Here's my code, not much at all:

Debug.Log("text is " + text);
input1 = float.Parse(text.ToString());
Debug.Log("Parsed string to " + input1);

It takes the user input text and converts it to a float.

  • 1
    12 * 100 is 1200, isn't it? `12E2` literally means `12 x 10²`. You want powers `Math.Pow(12, 2)`. – ProgrammingLlama Nov 27 '20 at 05:42
  • Nothing... What you want it to a do, is parse a mathematical expression, and its just not designed to do that. – TheGeneral Nov 27 '20 at 05:43
  • [Ask Dr. Math's explanation of exponent](http://mathforum.org/library/drmath/view/57140.html#:~:text=The%20e%20stands%20for%20Exponent,multiplied%20by%2010%20sixteen%20times): _"I get 1.524157875019e+16, which means that the answer is 1.524157875019 times 10 raised to the sixteenth power (that is, multiplied by 10 sixteen times)"_ – ProgrammingLlama Nov 27 '20 at 05:44
  • 1
    I have voted to reopen this question (not because I answered... well maybe a little) ... The close reason has no relevance to the question asked both in the title and the body of the question. "*What notation would be required to have it return a regular exponent* - The question (as far as the standards of stackoverflow go) is fine, even if it has a little misunderstanding in it. – TheGeneral Nov 27 '20 at 06:21
  • `12^2` is a math expression, not an integer literal – phuclv Nov 27 '20 at 06:39
  • [evaluating-a-mathematical-expression-in-a-string](https://stackoverflow.com/questions/2371436/evaluating-a-mathematical-expression-in-a-string) – Patrick Artner Nov 27 '20 at 10:57

1 Answers1

4

What you have (12E2) is standard scientific notation, and the results you are getting are correct 1200 (12*10^2). That is exactly what the E means, m × 10n.

Furthermore, there are no overloads or options to use Parse for regular power expressions. Parse is just not designed to do arbitrary mathematical operations (which is what you are asking)

You can however parse it your self to a certain degree and split on E or ^ or what ever you like really (assuming this is user input), then parse each component to pass into Math.Pow.

var someWeirdString = "12E2";

var array = someWeirdString.Split('E');

var someFloat = float.Parse(array[0]);
var someInt = int.Parse(array[1]);

var someResult = Math.Pow(someFloat, someInt);

Console.WriteLine(someResult);

Output

144
TheGeneral
  • 79,002
  • 9
  • 103
  • 141