S. Flynn
S. Flynn

Reputation: 45

Is a C# decimal cultural dependent

I'm going through some code from another developer and I found some code that seems... well ugly and unnecessary.

I understand that when parsing strings, we need to use cultural info properly when otherwise you can get into the "1.2" vs "1,2" type issues. In this case, the developer is using a NumericUpDown which is stored as a decimal.

float fValue = System.Convert.ToSingle(numericUpDown1.Value, System.Globalization.CultureInfo.InvariantCulture)

My questions are: - is the following code equivalent? - Will cultural info be handled properly?
- Can this cast throw an exception?

float fValue = (float)numericUpDown1.Value;

If they are not equivalent (or safe) can you please explain why and propose a "correct" solution?

Thanks in advance!

Upvotes: 2

Views: 312

Answers (2)

user7415073
user7415073

Reputation: 300

Yes, your code is equivalent to that only if the numericupdown1 value is small. but if that value is 41.00027357629127 or something like this it will return 4.10002732E+15.

so,by using float.Parse("numericUpDown1.Value", CultureInfo.InvariantCulture.NumberFormat); you can get the exact value

Upvotes: 0

user743382
user743382

Reputation:

Convert.ToSingle(value, culture) calls ((IConvertible)value).ToSingle(culture). decimal's IConvertible.ToSingle then ignores the passed-in culture and returns Convert.ToSingle(value), which just returns (float)value.

Yes, your code is equivalent.

Upvotes: 4

Related Questions