Question

I came across, something that I don't understand, using TryParse. I'm build a FormatConverter for my WPF app. A very standard FormatConverter. In the ConverBack function I've this code

Public Function ConvertBack(value As Object, targetType As Type, parameter As Object, culture As Globalization.CultureInfo) As Object Implements IValueConverter.ConvertBack
    Dim val As Double
    ' Here the value is "1495,00 $" and culture is "en-US"

    val = Double.Parse(value.ToString, Globalization.NumberStyles.Currency)
    If Double.TryParse(value.ToString, val) Then
        Return val
    End If

    Return 0
End Function

But the Odd thing about this, is Double.TryParse give me a False answer, and Double.Parse, convert the value correctly.

Why Double.TryParse, cannot convert the value??

Was it helpful?

Solution

Double.TryParse([string to convert], out result);

TryParse function which accepts two arrangements the first one is the string you want to convert and the second is the output parameter with the result value but the method it self return true or false based on conversion if conversion completed successfully then return true if not it will return false

Double.Parse([string to convert]);  

Parse function don't return true or false based on conversion it will try to convert if success it will return the value converted if not it will throw exception so if you want to use Parse function you have to place it in try and catch clause to avoid exceptions

UPDATE the problem you facing in the string format it self

Here is a method that most closely resembles the code you've provided

public static decimal Parse(string input)
{
   return decimal.Parse(Regex.Replace(input, @"[^\d.]", ""));
}

Here is an option that will support negative numbers, and will stop if it finds a second period value, thus reducing the number of strings it returns that are not valid decimal values. It also has a few other modifications not seen in the OP to handle additional cases your current code doesn't.

public static decimal Parse(string input)
{
    return decimal.Parse(Regex.Match(input, @"-?\d{1,3}(,\d{3})*(\.\d+)?").Value);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top