0

I do not understand why I have to specify NumberStyles.Float when using decimal.Parse and not for double.Parse

I can do:

var tmp = double.Parse("1e-2");

but not:

var tmp1 = decimal.Parse("1e-2"); 

Because a System.FormatException (Input string was not in a correct format) is thrown

var tmp1 = decimal.Parse("1e-2", System.Globalization.NumberStyles.Float);

someone can tell me if there is a good reason behind this behavior

giammin
  • 18,620
  • 8
  • 71
  • 89
  • Your screenshots seem to show a failure on line 15 *regardless* of what you're specifying. Your last one appears to show a problem on line 15 despite line 14 doing exactly the same operation. Really? – Jon Skeet Oct 14 '13 at 15:07
  • @JonSkeet I know, it's crazy. they are real. I'm not joking – giammin Oct 14 '13 at 15:10
  • Jon Skeet has an explanation [here](http://stackoverflow.com/questions/3879463/parse-a-number-from-exponential-notation) – Jonesopolis Oct 14 '13 at 15:11

1 Answers1

3

It's just behaving as documented. From Double.Parse:

The s parameter is interpreted using a combination of the NumberStyles.Float and NumberStyles.AllowThousands flags.

Note that NumberStyles.Float includes NumberStyles.AllowExponent.

From Decimal.Parse:

Parameter s is interpreted using the NumberStyles.Number style.

NumberStyles.Number does not include NumberStyles.AllowExponent.

I can't reproduce your bizarre stack traces which appear to show the same call failing just after it's worked:

  • Decimal.Parse("1e-2") always fails for me
  • Decimal.Parse("1e-2", NumberStyles.Float) always works for me
  • Double.Parse("1e-2") always works for me
  • Double.Parse("1e-2", NumberStyles.Float) always works for me

As for why the "default" number style differs between the two - I suspect it's because double values typically are used in scientific scenarios where exponent-based representations are common, but decimal values typically aren't.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Yes I know. I'm asking why this different behavior – giammin Oct 14 '13 at 15:11
  • @giammin: It would have been helpful if you'd said that beforehand - essentially you're asking why the default number formats are different, but your question doesn't ask that. I've added one paragraph at the end of my answer to suggest a possible reason. – Jon Skeet Oct 14 '13 at 15:13
  • Right: I modified my question to make it more clear. +1 for your answer! It is resonable. maybe it is from a performance point of view – giammin Oct 14 '13 at 15:19
  • @giammin: It sounds like you've actually got *two* questions then: 1) Why are the default styles different between the two types; 2) Why are you seeing odd behaviour. I've no idea about the latter, but I suspect it's not actually running the code you've got. I suggest you add extra diagnostic lines to prove that - and try to reproduce the problem in a console app. I also suggest you ask one question per post... – Jon Skeet Oct 14 '13 at 15:46