Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I have Decimal.TryParse parse 0.0?

Tags:

c#

.net

Is there a way to get Decimal.TryParse to parse a string value of "0.0" or "00.00" or "000.000" as 0?

I have tried setting NumberStyles to Any.

like image 881
Aaron Fischer Avatar asked Jan 26 '10 22:01

Aaron Fischer


People also ask

How to use decimal TryParse in c#?

TryParse(value, style, culture, number) Then Console. WriteLine("Converted '{0}' to {1}.", value, number) Else Console. WriteLine("Unable to convert '{0}'.", value) End If ' Displays: ' Converted '1345,978' to 1345.978. value = "1.345,978" style = NumberStyles.

How do you convert a decimal to a string?

To convert a Decimal value to its string representation using a specified culture and a specific format string, call the Decimal. ToString(String, IFormatProvider) method.

What is the purpose of the decimal parse method?

Converts the string representation of a number to its Decimal equivalent.

How do you convert decimals to integers?

A user can also convert a Decimal value to a 32-bit integer by using the Explicit assignment operator. Syntax: public static int ToInt32 (decimal value); Here, the value is the decimal number which is to be converted. Return Value: It returns a 32-bit signed integer equivalent to the specified value.


1 Answers

Using the InvariantCulture, decimal.TryParse does successfully interpret all of those strings as zero. This code, for example:

decimal num = 66;
foreach (var str in new string[] { "0.0", "00.00", "000.000" })
{
    if (!decimal.TryParse(str, out num))
    {
        Console.WriteLine( "fail" );
    }
    Console.WriteLine(num);
}

Produces this output:

0.0
0.00
0.000

Perhaps, the issue is printing the values, not parsing the values? If that's the case, simply use a format string that specifies that the decimal places are optional.

Console.WriteLine( num.ToString( "#0.#" ) );

Produces

0
0
0
like image 195
tvanfosson Avatar answered Sep 22 '22 00:09

tvanfosson