Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

VB.Net convert formatted string to double

I got a string by formatting a double value, like

Dim strFormat = "#,##0.00 weeks"
Dim strDisplayText As String = dblIn.ToString(strFormat) ' dblIn is type Double

Then the strDisplayText is displayed in a textbox (of a wpf.datagrid), and the user may edit it. Afterwards, the text should be converted back to an double.

Dim dblOut = ???(strDisplayText, strFormat)
 ' dblOut should be the same as dblIn, if strDisplayText wasnt changed.
if dblOut.ToString(strFormat) <> strDisplayText Then
    print("failed conversion.")
end if

Double.Parse (and TryParse) fail because of the " weeks" at the end and Val cant process the "," as group seperator.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

strFormat is read from a file, so it might be any valid custom or standart numeric format (https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings or https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-numeric-format-strings)

>Solution :

You can use simple string methods to remove the " weeks" at the end:

Dim dblValue = strDisplayText.Remove(strDisplayText.Length - " weeks".Length)
Dim dbl As Double = double.Parse(dblValue)

strFormat is read from a file, so it might be any valid custom or
standart numeric format

You cannot revert a text that was formatted with an arbitrary format string to the double value. There is no Double.TryParseExact(like for Date). Especially if you even have different decimal or group separators.

I’d let the user edit the double value, not the formatted text.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading