user3473957
user3473957

Reputation: 89

Convert a number and accept any decimal separator

I have a double number 0,401780062641746

I want to format it to 0.40178006

I'm using this code:

string.Format("{0:0.00000000%}", dNum);

But the result is 40.17800626

I want to be able to type either . or , for decimal separator. So I'm using

NumberStyles.Any

Example:

double.TryParse(textBox1.Text, NumberStyles.Any, CultureInfo.InvariantCulture, out dNum);

but apparently that's a problem and now I can't convert the number the way I want.
Any ideas?

Upvotes: 0

Views: 178

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503090

If you only need to cope with decimal points, so you don't need to handle grouping separators, the simplest option would be to just replace any commas with dots:

string input = ...;
input = input.Replace(',', '.');
double value;
if (double.TryParse(input, CultureInfo.InvariantCulture))
{
    // Use value
}
else
{
    // Handle invalid input
}

Note that this will only cope with . and , as decimal separators, and won't perform any other culture-specific parsing.

Upvotes: 1

Related Questions