Zapnologica
Zapnologica

Reputation: 22556

c# double.parse() to always use a . period not comma

How can I specify that my decimal.Parse must always expect to receive a string with a '.' like "4.75" no mater what the system settings of the computer are?

I am reading in a file from excel and it gives me value with a '.' and I see that if I run my program on my laptop It throws and error as it expects a ','

I can use:

string tmp1 = tmp[2].Replace('.', ',');

but then obviously if my computer wants a ''. then it will give an error.

What is my best option?

Upvotes: 4

Views: 8331

Answers (3)

Dustin Kingen
Dustin Kingen

Reputation: 21245

See: Double.Parse

Use this overload to specify an IFormatProvider in your case CultureInfo.InvariantCulture.

var value = double.Parse(tmp[2], CultureInfo.InvariantCulture);

However I would recommend Double.TryParse if you intend to make your process durable.

double value;

if(!double.TryParse(tmp[2],
   NumberStyles.None,
   CultureInfo.InvariantCulture,
   out value))
{
    // error handling
}

Upvotes: 11

Reed Copsey
Reed Copsey

Reputation: 564441

You could use the overload of Decimal.Parse which will allow you to specify a culture:

decimal value = decimal.Parse(tmp[2], CultureInfo.InvariantCulture);

Upvotes: 4

Habib
Habib

Reputation: 223277

Use Double.Parse Method (String, IFormatProvider) with CultureInfo.InvariantCulture for parsing.

double d = double.Parse("2.2", CultureInfo.InvariantCulture);

Upvotes: 7

Related Questions