I have this line of code:
System.Convert.ChangeType(input, destinationType, CultureString);
If called with a culture of de-DE and input is 4,50 and destinationType is double it returns 4.50.
If I call the same with en-GB it converts it to 450.00.
Is there a way to make it return 4.50 or throw an exception saying you can’t convert 4,50 to double.
Thanks
As specified from MSDN on the specific overload you are using:
In other words, it tries to understand how to convert based on the culture’s formatting information. So
4,50means4.5in de-DE yet the same number is identified as4.50in en-GB (Notice there is a period not a comma).A comma is used in the en-GB culture to talk about thousands (e.g 4000 can be written
4,000) when 4,50 is parsed, the comma is ignored and therefor the output is 450.This is just like the date 21st of January 2010 is parsed
01/21/10(mm/dd/yy) in the US yet it is parsed21/01/10(dd/mm/yy) in the UK.So actually, no exception should be raised since 4,50 CAN be converted to a double, depends where in the world 🙂
Note: C# has the CultureInfo.InvariantCulture when you want culture-independent conversions.
If you want to throw an exception, don’t use ChangeType, use
Double.Parsewith theNumberStylesjust like @ChrisF explained in his answer.This for instance will throw an exception: