6 Replies - 8571 Views - Last Post: 27 February 2011 - 12:25 PM Rate Topic: -----

#1 BMtne  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 27-February 11

Formatting decimal places

Posted 27 February 2011 - 02:59 AM

Hi, I'm pretty new to VB and I had a question regarding decimals. I have designed a unit converter that converts between different units. The value and unit to be converted from are entered in the first text box, for example "1 km" and the unit to be converted to is entered in the second text box. Then after pressing the calculate button, the new value will be displayed in the second text box as the output. By default the output will be specified to two decimal places. However, if the input has any number of decimal places, for example "1.045 km" the output should be displayed to the same decimal place, in this case 3.

Displaying the output to two decimal places was easy enough to figure out, I just used:
 FormatNumber(finalValue, 2) 

But I'm completely stuck on the other part however and I'm wondering if anyone here has any suggestions. I thought about doing something like this:
 Dim m, n As Integer
Dim decStr As String
m = txtInput.IndexOf(".") 'to find the position of the decimal point
n = txtInput.IndexOf(" ") 'to find the position of the space
decStr = txtInput.Substring(m, n)


Now this code unfortunately doesn't work at all (lol), but its the only idea I have right now. Basically I'm looking to find a way to figure out what position the decimal point is at and what position the space is at, take the substring of that, figure out the length of the substring and then use that integer value in the FormatNumber function for the output.

Then once that's done I'll just an If block to switch between the default two decimal places and the input decimal places.

So if anyone has any tips or feedback or alternative ideas I'd really appreciate the help.

Is This A Good Question/Topic? 0
  • +

Replies To: Formatting decimal places

#2 November-06  Icon User is offline

  • D.I.C Regular

Reputation: 45
  • View blog
  • Posts: 376
  • Joined: 04-January 11

Re: Formatting decimal places

Posted 27 February 2011 - 04:08 AM

Try using .Split to get the decimal part and then .Length to get the number of decimal places.

Dim DecimalPart As String() = txtInput.text.Split(New Char() {"."c})
'This will split the parts being divided by the decimal point
'The whole number is placed at Decimalpart(0)
'The decimal is placed at Decimalpart(1) so...
Dim DecimalPlaces as Integer
DecimalPlaces = DecimalPart(1).Length
'This will get the number of decimal places



Try using this code above. Please vote this post up if it helps.
Was This Post Helpful? 0
  • +
  • -

#3 dbasnett  Icon User is offline

  • D.I.C Addict

Reputation: 102
  • View blog
  • Posts: 584
  • Joined: 01-October 08

Re: Formatting decimal places

Posted 27 February 2011 - 08:27 AM

Give this a try

        Dim smplTB As String = "1,000.045 km" 'simulated textbox entry
        Dim parts() As String = smplTB.Split(New Char() {" "c}, StringSplitOptions.RemoveEmptyEntries)
        parts(0) = parts(0).Replace(",", "")
        Dim valPart As Double
        Dim unitPart As String
        Dim numDecs As Integer = 0
        If Double.TryParse(parts(0), valPart) Then
            'valid number
            unitPart = parts(1)
            Debug.WriteLine(unitPart & " " & valPart.ToString)
            If parts(0).IndexOf("."c) <> -1 Then
                numDecs = parts(0).Length - parts(0).IndexOf("."c) - 1
            End If
            Debug.WriteLine(numDecs.ToString)
        End If


        Stop


This post has been edited by dbasnett: 27 February 2011 - 08:42 AM

Was This Post Helpful? 1
  • +
  • -

#4 CharlieMay  Icon User is offline

  • This space intentionally left blank
  • member icon

Reputation: 1533
  • View blog
  • Posts: 4,919
  • Joined: 25-September 09

Re: Formatting decimal places

Posted 27 February 2011 - 10:01 AM

Your code is close, however the second parameter of the substring is length. And since this is variable due to input you will need to calculate from the two indexof values you have.

Let's take 123.456 km

m = 3 'don't forget we start at 0 so the period is at index 3

n = 7 'space is at index 7

your substring is pulling part of a string starting at position 3 and taking 7 characters total.

Now, we can't use m as it stands because that starts taking characters at the period. So we need to add one to the position
We definitely know we can't use n as a length of 7 is out of bounds for this particular string and even if it wasn't would not produce the proper results anyway.

We can subtract m from n and we get 4 (now we're close) but this result will give us .456 so we have to perform some more math

If we add 1 to M in the start position that moves our starting position to 4 which is correct but that will leave us with ".456 " and we don't want the space. So we just need to make sure that on the Length parameter we add 1 to m before we subtract it from n.
decStr = txtInput.SubString(m + 1, n - (m + 1))

So we know m is 3 and n is 7
m + 1 = 4 'That will get us to the 4th position of the string which is what we want.
7-(3+1) = 7-4 = 3 'That is the number of characters between the period and the space.
"123.456 km" the substring(4,3) would result in 456 and now decStr.Length = 3 telling you how many decimal places you have.
Was This Post Helpful? 1
  • +
  • -

#5 November-06  Icon User is offline

  • D.I.C Regular

Reputation: 45
  • View blog
  • Posts: 376
  • Joined: 04-January 11

Re: Formatting decimal places

Posted 27 February 2011 - 10:24 AM

I didn't see the km part. Let me revise the code I have written above.


Dim Measurement As String() = txtInput.text.Trim.Split(New Char() {" "c})
'This will remove unneccessary spaces in front and at the end then split the input being divided by a space

'Measurement(0) will the numeric value and Measurement(1) will have the unit

Dim DecimalPart As String() = Measurement(0).Split(New Char() {"."c})
'This will split the parts being divided by the decimal point
'The whole number is placed at Decimalpart(0)
'The decimal is placed at Decimalpart(1) so...
Dim DecimalPlaces as Integer
DecimalPlaces = DecimalPart(1).Length
'This will get the number of decimal places




Hope this helps.

This post has been edited by November-06: 27 February 2011 - 10:25 AM

Was This Post Helpful? 1
  • +
  • -

#6 BMtne  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 27-February 11

Re: Formatting decimal places

Posted 27 February 2011 - 11:41 AM

Thanks everyone I wasn't expecting so many replies lol. I'm glad to know that my original code wasn't too far off from what it needed to be. I figured it out using CharlieMay's suggestions. Thank you to everyone who took the time to answer though, up votes for everyone!
Was This Post Helpful? 0
  • +
  • -

#7 dbasnett  Icon User is offline

  • D.I.C Addict

Reputation: 102
  • View blog
  • Posts: 584
  • Joined: 01-October 08

Re: Formatting decimal places

Posted 27 February 2011 - 12:25 PM

View PostNovember-06, on 27 February 2011 - 11:24 AM, said:

I didn't see the km part. Let me revise the code I have written above.


Dim Measurement As String() = txtInput.text.Trim.Split(New Char() {" "c})
'This will remove unneccessary spaces in front and at the end then split the input being divided by a space

'Measurement(0) will the numeric value and Measurement(1) will have the unit

Dim DecimalPart As String() = Measurement(0).Split(New Char() {"."c})
'This will split the parts being divided by the decimal point
'The whole number is placed at Decimalpart(0)
'The decimal is placed at Decimalpart(1) so...
Dim DecimalPlaces as Integer
DecimalPlaces = DecimalPart(1).Length
'This will get the number of decimal places




Hope this helps.



What happens if there is not a "." present?


Here is some code with some test cases.

    Private Sub Button1_Click(ByVal sender As System.Object, _
                              ByVal e As System.EventArgs) Handles Button1.Click

        Dim testCases() As String = New String() {"", _
                                                  "1,000.0456 km", _
                                                  " km 1,000.0456", _
                                                  "km", _
                                                  "1 km", _
                                                  "1000 mi", _
                                                  "33.4 m", _
                                                  ".045 ft", _
                                                  "0.045 ft"}
        Debug.WriteLine("")
        For Each t As String In testCases
            'show the original input
            Debug.WriteLine("tb = " & t)
            getTextBoxInfo(t)
        Next

    End Sub

    Private Sub getTextBoxInfo(ByVal theText As String)
        Debug.WriteLine("results")
        Dim smplTB As String = theText
        Dim parts() As String = smplTB.Split(New Char() {" "c}, StringSplitOptions.RemoveEmptyEntries)
        If parts.Length > 1 Then
            parts(0) = parts(0).Replace(",", "")
            Dim valPart As Double
            Dim unitPart As String
            Dim numDecs As Integer = 2 'defualt number of decimals
            If Double.TryParse(parts(0), valPart) Then
                'valid number
                unitPart = parts(1)
                If parts(0).IndexOf("."c) <> -1 Then
                    numDecs = parts(0).Length - parts(0).IndexOf("."c) - 1
                End If
                Dim fmt As String = "n" & numDecs
                'show results
                Debug.WriteLine("Units = {0},  Value = {1},  Number of decimals =  {2}", unitPart, valPart.ToString(fmt), numDecs)
            End If
        End If
    End Sub


Was This Post Helpful? 0
  • +
  • -

Page 1 of 1