Link to home
Start Free TrialLog in
Avatar of xlmaster200
xlmaster200

asked on

Convert.ToDouble with negative number on OS X

Hi,

In our Silverlight applicaiton when we uses Convert.ToDouble("-1") on an OS X (10.7) it crashes with:
"Unhandled Error in Silverlight 4 Application [Format_InvalidString]"

Any negative values will crash.

Even if we run a virtual Windows on the mac it will crash with the same error message. On a clean Windows machine it works fine.

Any help appreciated.
Avatar of nishant joshi
nishant joshi
Flag of India image

try to cast if convert not works well.

(Double)"-1";
Avoid exception using TryParse method.

if(Double.TryParse("-1") != null )
   Convert.ToDouble("-1");

Try to use Double.Parse("-1") then.

Avatar of xlmaster200
xlmaster200

ASKER

I could try to cast it but I'd really liked to now if anyone can explain why it's not working, is it a bug in the runtime?


ASKER CERTIFIED SOLUTION
Avatar of smickle
smickle

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks for your answer Steve.
So in other words I can't use Convert.ToDouble (or Convert.ToInt16) anywhere in the code...
I did some test on the client side for a Mac:
string s = "-1";
double d =Convert.ToDouble(s)   - Unhandled Error in Silverlight 4 Application [Format_InvalidString]
double d = Double.Parse(s)  - Unhandled Error in Silverlight 4 Application [Format_InvalidString]
double d = Double.Parse(s,CultureInfo.InvariantCulture) - OK

What culture does not accept "-" before a number? If I try cdbl("-1") in a VBA macro on the Mac it works OK.

It feels no good to change Convert.ToDouble everywhere in the code.
I printed out CultureInfo.CurrentCulture.NumberFormat.NegativeSign and found that on the Mac the NegativeSign was a little longer than in Windows... Silly me not thinking of that...

So I go with your suggestion Steve and use InvariantCulture on the client side
Ha, extra long negative sign. That's great.

You might be able to get around changing all the code, and you can explicitly set your desired culture in web.config, if this is an asp.net app. Not sure if this will work off the top of my head, but it could. This would ensure that all your conversions in your code that run within your web app will use a preset culture.

 
<!-- system.web section inside your web.config -->
<globalization culture="en-US"/>

Open in new window


Globalization can be a headache in many sneaky ways though. Especially if you have values stored and retrieved from SQL Server for example. And the SQL Server has a different culture setting than the code that uses it. They must match in order to get predictable results. DateTime formats and conversions are the main ones that get hosed in that scenario due to the different order of the mm/dd/yy structure.