Converting Doubles to Strings
Converting Doubles to Strings
Converting Doubles to Strings
Converting Doubles to Strings
Converting Doubles to Strings
Converting Doubles to Strings Converting Doubles to Strings Converting Doubles to Strings Converting Doubles to Strings Converting Doubles to Strings Converting Doubles to Strings Converting Doubles to Strings Converting Doubles to Strings
Converting Doubles to Strings Converting Doubles to Strings
Converting Doubles to Strings
Go Back  Xtreme Visual Basic Talk > > > Converting Doubles to Strings


Reply
 
Thread Tools Display Modes
  #1  
Old 09-23-2011, 06:58 PM
MrMuffles MrMuffles is offline
Newcomer
 
Join Date: Oct 2010
Posts: 8
Default Converting Doubles to Strings


I apologize in advance if there is a thread for this. I've used the search tool but did not find a simple answer to what I'm looking for. (I assume it's rather simple)

I'm trying to convert doubles to strings for the sole purpose of putting them on a label. CStr seems to chop off the decimals, as does ToString.

After 20 minutes of googling around, I'm seeing there are format options but none seem to be doing the trick and/or I'm just not doing it right. Could someone enlighten me on this subject?

Thanks in advance.

PS: These are only 2 decimal place doubles, aka 0.29, 1.47, etc.
Reply With Quote
  #2  
Old 09-23-2011, 08:51 PM
AtmaWeapon's Avatar
AtmaWeaponConverting Doubles to Strings AtmaWeapon is offline
Fabulous Florist

Forum Leader
* Guru *
 
Join Date: Feb 2004
Location: Austin, TX
Posts: 9,500
Default

Composite Formatting and Standard Numeric Format Strings are useful topics.

In this case, note there's a Double.ToString() overload that takes a format string. The "F" standard numeric format string means you want the number displayed with a fixed decimal point. If you only want 2 places, you can specify a field width of 2 using the syntax from Composite Formatting. ToString() doesn't need the {} from the formatting article, so here's two ways to get where you want:
Code:
Dim value As Double = 1.23456
Dim str As String = value.ToString("F2")
str = String.Format("{0:F2}", value)
I tend to use String.Format() more often because it's more generally useful, but there's no reason to choose one over the other in this case.
__________________
.NET Resources
My FAQ threads | Tutor's Corner | Code Library
I would bet money 2/3 of .NET questions are already answered in one of these three places.
Reply With Quote
  #3  
Old 09-23-2011, 09:24 PM
MrMuffles MrMuffles is offline
Newcomer
 
Join Date: Oct 2010
Posts: 8
Default

Sweet, this works perfectly. However, I've encountered a new problem. It was still showing things like "0.00" and "1.00" and I've traced it back to a CDbl function.

Is there an extra parameter or a better method to converting to a double? (I'm taking these numbers from a file; they're read as a string then converted appropriately.)
Reply With Quote
  #4  
Old 09-23-2011, 10:02 PM
AtmaWeapon's Avatar
AtmaWeaponConverting Doubles to Strings AtmaWeapon is offline
Fabulous Florist

Forum Leader
* Guru *
 
Join Date: Feb 2004
Location: Austin, TX
Posts: 9,500
Default

It all depends on what the numbers look like in the file and how you're converting them.

CDbl() is the least powerful of all methods to convert to a Double. It's not a conversion, it's a cast. The difference is subtle, but it's more like you're saying, "What I have should already be a Double, do the simplest thing that could result in a number." What you want is parsing, and it gives you many choices.

If I could see the input data and examples of what you think the results should look like, I could help you better.

But here's a better question. If the numbers come out of a file and you already have them as strings, why convert them to Doubles just to convert them back to strings again? That's extra work. Perhaps it'd be more clear with more details.
__________________
.NET Resources
My FAQ threads | Tutor's Corner | Code Library
I would bet money 2/3 of .NET questions are already answered in one of these three places.
Reply With Quote
  #5  
Old 09-23-2011, 10:12 PM
MrMuffles MrMuffles is offline
Newcomer
 
Join Date: Oct 2010
Posts: 8
Default

Thanks for the quick responses, I appreciate it.

As mentioned in another thread of mine not too long ago, this is that weather program I was talking about. The lines in a file look like this:
Code:
1993,1,2,55,48,-1,0.29,x
'(Year, Month, Day, High, Low, Wind, Rain, Comments)
And the code that loads the entire weather csv into memory is:
Code:
   Public Sub LoadWeather()
        Dim tempLine As String
        Dim tempSplit() As String
        Dim sFileName As String = Application.StartupPath & "\WeatherData.csv"
        Dim myFileStream As New System.IO.FileStream(sFileName, FileMode.OpenOrCreate, FileAccess.Read, FileShare.Read)
        Dim sRead As New System.IO.StreamReader(myFileStream)

        Do While sRead.Peek > -1
            Dim eWeather As New Weather()

            tempLine = sRead.ReadLine
            tempSplit = tempLine.Split(Convert.ToChar(","))

            eWeather.High = CInt(tempSplit(3))
            eWeather.Low = CInt(tempSplit(4))
            eWeather.Wind = CInt(tempSplit(5))
            eWeather.Rain = CDbl(tempSplit(6))
            eWeather.Comment = tempSplit(7)

            '---***** Test condition *****---
            If tempSplit(0) = "1993" Then
                MessageBox.Show(eWeather.Rain.ToString("F2")) 'This message box is showing "0.00"
                MessageBox.Show(tempSplit(6)) 'This message box is showing "0.29"
            End If
            '---***************************---

            iPWeather(CInt(tempSplit(0)) - SUB_YEARS, CInt(tempSplit(1)) - 1, CInt(tempSplit(2)) - 1) = eWeather
        Loop

        sRead.Close()
        myFileStream.Close()
    End Sub
Everything is working wonderfully minus this annoying double issue. The reason I convert them to their proper numbers is because there's a lot of arithmetic with averages, sums, comparisons, etc.

And as you can see by the "Test condition" section in the code, I check the variable after it has been converted and before it was converted. The decimals are getting lost in that conversion.

Last edited by MrMuffles; 09-23-2011 at 10:19 PM.
Reply With Quote
  #6  
Old 09-24-2011, 06:23 AM
AtmaWeapon's Avatar
AtmaWeaponConverting Doubles to Strings AtmaWeapon is offline
Fabulous Florist

Forum Leader
* Guru *
 
Join Date: Feb 2004
Location: Austin, TX
Posts: 9,500
Default

If it's broken down to the simplest possible code, it works fine:
Code:
        Dim tempLine = "1993,1,2,55,48,-1,0.29,x"
        Dim tempSplit = tempLine.Split(Convert.ToChar(","))

        Dim value As Double = CDbl(tempSplit(6))
        MessageBox.Show(value.ToString("F2"))
I don't see enough code to know why it's not working for you. If I had to take a psychic guess (and I didn't sleep last night so it's fuzzy) I reckon I'd pick, "Weather.Rain is not of type Double, and you have Option Strict off so it gets coerced to an integral type."
__________________
.NET Resources
My FAQ threads | Tutor's Corner | Code Library
I would bet money 2/3 of .NET questions are already answered in one of these three places.
Reply With Quote
  #7  
Old 09-24-2011, 05:10 PM
azuckerman's Avatar
azuckerman azuckerman is offline
Newcomer
 
Join Date: Sep 2011
Location: Texas, USA
Posts: 13
Default

If CDbl can't cast the value to a numeric type, then it will throw an exception. Since you are not catching any errors in the code above, you may need to start looking in that direction. A variable of the type double will be initialized to 0.0 upon creation of the variable.

One other thing I noticed when looking at your code: you are assuming that the temperatures are all going to be integers. There are times when things won't parse correctly, especially when you have comments and are using a typeable character as a separator (in this case a comma and the CRLF pair in the comments).
Reply With Quote
Reply


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off

Forum Jump

Advertisement:





Free Publications
The ASP.NET 2.0 Anthology
101 Essential Tips, Tricks & Hacks - Free 156 Page Preview. Learn the most practical features and best approaches for ASP.NET.
subscribe
Programmers Heaven C# School Book -Free 338 Page eBook
The Programmers Heaven C# School book covers the .NET framework and the C# language.
subscribe
Build Your Own ASP.NET 3.5 Web Site Using C# & VB, 3rd Edition - Free 219 Page Preview!
This comprehensive step-by-step guide will help get your database-driven ASP.NET web site up and running in no time..
subscribe
Converting Doubles to Strings
Converting Doubles to Strings
Converting Doubles to Strings Converting Doubles to Strings
Converting Doubles to Strings
Converting Doubles to Strings
Converting Doubles to Strings Converting Doubles to Strings Converting Doubles to Strings Converting Doubles to Strings Converting Doubles to Strings Converting Doubles to Strings Converting Doubles to Strings
Converting Doubles to Strings
Converting Doubles to Strings
 
Converting Doubles to Strings
Converting Doubles to Strings
 
-->