2

I have a function in VB.NET that loops through values and attempts to convert it to a decimal if IsNumeric is True,

Dim Value As String

If IsNumeric(Value) = True Then
    Rate = CType(Value, Decimal)  <--- bombing here
End If

I've found that when the function receives the value 603E43 IsNumeric evaluates to True for some reason and then bombs on the conversion. Why would IsNumeric be true in this case?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • 4
    Because `603E43` is a semi-standard numerical representation of a floating point value, in particular: `603*10^43`. I have no idea how `CType` works (as I don't use VB.NET ;-), but in C# I'd might use `decimal.TryParse`. `IsNumeric` is likely more related to the SQL Server "numeric" rules, which also include leading dollar signs, etc. I can't seem to find any official "full" rules. –  Jul 21 '11 at 00:37
  • what do you mean by bombing ? what is the error message/exception ? – Yahia Jul 21 '11 at 00:39
  • Perhaps see this [VB6 SO question about IsNumeric](http://stackoverflow.com/questions/470041/vb6-can-isnumeric-be-wrong) ... I am assuming VB.NET's IsNumeric is a good clone ;-) –  Jul 21 '11 at 00:44
  • @pst, Ah that sounds correct. Many thanks for the info. – Michael Broniola Jul 21 '11 at 00:47
  • 2
    On another point you dont need the `= True` part. Just say `If IsNumeric(Value) Then ...` – John Alexiou Jul 21 '11 at 00:50
  • Dim x As Double Dim y As String = "1e3" If IsNumeric(y) Then x = CDbl(y) results in x=1000 – Martin Jul 21 '11 at 14:20

1 Answers1

10

See http://support.microsoft.com/kb/329488

IsNumeric returns true if it can be converted to a double which is true for 603E43 The value is however larger than what a decimal can hold

You could use the Decimal.TryParse funcion as a working alternative. See http://msdn.microsoft.com/en-us/library/9zbda557.aspx

Eddy
  • 5,320
  • 24
  • 40
  • 5
    Personally, I've dumped using `IsNumeric` in favour of `.TryParse` in all circumstances. It's far more robust. – Hand-E-Food Jul 21 '11 at 00:57
  • 2
    Ahh +1. This got me. I was about to say: "but a decimal is a wider type" because the *size* of decimal value is twice that of a double (128 vs 64 bits) -- yet the *range* is far less (while the *precision* is much higher). The *range* of decimal is +/- 10^28 while a double is +/- 10^308 (give or take). –  Jul 21 '11 at 01:01