user3144640
user3144640

Reputation: 113

Formatting Numbers as Strings with point in place of Decimals no matter Culture

WinForms, I have a textbox leave event, in the textbox the user is prompted to add a price example:

He needs to provide the price in the textbox let's say he writes 5 only, the textbox leave event should get him 5.00 and it's working but there is a problem on other computers that use other culture for example in that computer that I encountered the problem Point '.' this is treated as comma this ',' and if user prompts 5.43 he will get 543,00 not 5.43 or 5 to get 5.00 he will get comma. I need to get for every computer no matter the culture to work only with Point this '.' here is my code:

decimal number = 0;
if (Decimal.TryParse(textBox20.Text, out number))
{
   textBox20.Text = Decimal.Parse(textBox20.Text).ToString("0.00");
}
else
{
   textBox20.Text = "0.00";
}

Upvotes: 0

Views: 283

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503869

Just use the overload of decimal.TryParse which takes an IFormatProvider, and specify the invariant culture. Then use that for formatting, too. (I'm assuming you want it to be treated consistently as "dot for the decimal separator" on both parsing and formatting.)

Oh, and only parse once - why do it twice?

decimal number = 0;
if (Decimal.TryParse(textBox20.Text, NumberStyles.Number,
                     CultureInfo.InvariantCulture, out number))
{
    textBox20.Text = number.ToString("0.00", CultureInfo.InvariantCulture);
}
else
{
    textBox20.Text = "0.00";
}

Given that 0 will be formatted that way as well, you don't even need anything to be conditional:

decimal number;
decimal.TryParse(textBox20.Text, NumberStyles.Number,
                 CultureInfo.InvariantCulture, out number);
textBox20.Text = number.ToString("0.00", CultureInfo.InvariantCulture);

We don't care about the return value of TryParse in this case, because if it fails, number will be 0, which is fine...

Upvotes: 1

Related Questions