2

I want to convert a very Small number to Decimal,

Lets Say

String secondsStr = 0;
Decimal secondsValue;
Boolean success = Decimal.TryParse(secondsStr, out secondsValue);

But the problem is I have the string representation of it, 3.24E-08

String secondsStr = 3.24E-08;
Decimal secondsValue;
Boolean success = Decimal.TryParse(secondsStr, out secondsValue);

It always return success as false.

How can I parse that to get 0.00000003244657 ?

David
  • 3,957
  • 2
  • 28
  • 52
Pankaj
  • 2,618
  • 3
  • 25
  • 47
  • How are you going to use the 'very small number'? If it is for display purposes, you could treat it as a string. – aquaraga Jun 10 '13 at 10:41
  • @Chris: By the way, the accepted answer in the proposed duplicate which suggests to use `NumberStyles.Float` does not work with the string above. – Tim Schmelter Jun 10 '13 at 10:52
  • @Tim, I agree, NumberStyles.Float didn't worked for me where as NumberStyles.Any did – Pankaj Jun 10 '13 at 10:56
  • @TimSchmelter: Strange. In linqpad I run `Double.Parse("3.24E-08", System.Globalization.NumberStyles.Float)` and it works fine... – Chris Jun 10 '13 at 10:57
  • @Chris: I assume the current culture is responsible. So either use `NumberStyles.Any` as i have suggest below or use `CultureInfo.InvariantCulture` as third argument. – Tim Schmelter Jun 10 '13 at 11:06

2 Answers2

5

You can use TryParse with the NumberStyles argument:

var ok = Decimal.TryParse(secondsStr, NumberStyles.Any, null, out secondsValue);

I have used NumberStyles.Any which works.

Indicates that all styles except AllowHexSpecifier are used. This is a composite number style.

Update: if it works with NulberStyles.Float depends on the current culture. If it uses . as decimal separator it works. So you can also use CultureInfo.InvariantCulture as third argument:

var ok = Decimal.TryParse(secondsStr, NumberStyles.Float, CultureInfo.InvariantCulture, out secondsValue);
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
0

Try this

 Boolean c= decimal.TryParse("3.24E-08", System.Globalization.NumberStyles.Float, null, out a);
Sathish
  • 4,419
  • 4
  • 30
  • 59