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.
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.
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.
Converts the string representation of a number to its Decimal equivalent.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With