Question How to convert String to Double?

raysefo

Well-known member
Joined
Jul 21, 2010
Messages
207
Programming Experience
Beginner
Hi,

I have 17000.00 as String and i want to convert it to double. When i use like below i get 170000.0.



Dim str As String = "17000.00"
VB.NET:
Dim num As Double = System.Convert.ToDouble(str)

Thanks in advance.

Best Regards
 
First off, with doubles x.00 will always be x.0, the only way to get 2 decimal places is to have a number that's 2 decimal place and those numbers aren't 00, ie you need .01 or .21, etc...

2nd, you should be using Double.Parse() or Double.TryParse() unless you know for sure the string will always be a number that can be converted to a decimal.
 
Numerically, what is the difference between 0 and 0.00 ?


Nothing

If you want a number to have a certain look when you print it or show it to the user, that is the time at which you format it
 
I'm not sure if that was a typo though...

OP (rayfeso) you said you put in 17000.00 (17 thousand) and get back 170000.0 (17 hundred thousand). Is that your problem? If so I'd look at any math you're doing after the convert because the conversion works just fine.

Also if you want to convert a double back to a string with some type of fixed length like that... here:

VB.NET:
Dim str As String = "17000.00"
Dim value As Double = Convert.ToDouble(str)

Console.WriteLine(value.ToString("#.00"))

that will result in just 2 spaces after the decimal point. You can even format with some ',' if you want... like so:

value.ToString("#,###.00")
 
Last edited:
I'm not sure if that was a typo though...

OP (rayfeso) you said you put in 17000.00 (17 thousand) and get back 170000.0 (17 hundred thousand). Is that your problem? If so I'd look at any math you're doing after the convert because the conversion works just fine.

Also if you want to convert a double back to a string with some type of fixed length like that... here:

VB.NET:
Dim str As String = "17000.00"
Dim value As Double = Convert.ToDouble(str)

Console.WriteLine(value.ToString("#.00"))

that will result in just 2 spaces after the decimal point. You can even format with some ',' if you want... like so:

value.ToString("#,###.00")
That will omit the decimal altogether if there are numbers (other than 0) after the decimal.

I would use .ToString("n2") instead so it would show "123.00" as well as "123.45" if there is a decimal to be shown.

I still can't stress the Double.TryParse() enough.
 
you're right, sorry about that... it'd be "#.##" or "n2"


[edit]
wait no, .00 works fine... it doesn't replace with 0's, just tested.
 
Last edited:
Back
Top