none
Formating Decimal. RRS feed

  • Question

  • What is the best / easiest way to format a decimal

    We need minimum 1 decimal but upto 3 decimal points or 4 in some cases..

    i mean for eg. if text is 12.000 then we need to show 12.0

    and if value is 12.010 then 12.01

    and it value is 12.001 then 12.001

    Again at least 1 decimal is must we can not show 12

    Please help..


    Pradeep Yadav (Social MSDN)

    Tuesday, April 23, 2019 1:19 PM

All replies

  • In short if you have values as seen here

    Dim values As String() = {"12.000", "12.010", "12.0133","23"}

    And you want to format them as per described first make sure the value can represent a double then once that is done use .ToString to format it which will be exactly the same as the original values so in a sense this does not make sense in regards to your question unless I'm missing something.

    The following is a basic example which could be perhaps optimized and made into a language extension method.

    Public Class Form1
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Dim values As String() = {"12.000", "12.010", "12.0133", "23"}
    
            Dim result As Double
            For Each value In values
                If value.ToString().Contains(".") Then
                    Dim parts = value.Split("."c)
                    If Double.TryParse(value, result) Then
                        Console.WriteLine(result.ToString($"N{parts(1).Length}"))
                    End If
                Else
                    Console.WriteLine($"{value}.00")
                End If
            Next
        End Sub
    End Class
    

    Results

    12.000
    12.010
    12.0133
    23.00


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Tuesday, April 23, 2019 1:40 PM
    Moderator
  • Hi

    Here is one way. Note the String format used is the same for all inputs.

            Dim str1 As String = "12"
            TextBox1.AppendText(CDbl(str1).ToString("0.0###") & vbCrLf) ' 12.0
            str1 = "12.0"
            TextBox1.AppendText(CDbl(str1).ToString("0.0###") & vbCrLf) ' 12.0
            str1 = "12.01"
            TextBox1.AppendText(CDbl(str1).ToString("0.0###") & vbCrLf) ' 12.01
            str1 = "12.001"
            TextBox1.AppendText(CDbl(str1).ToString("0.0###") & vbCrLf) ' 12.001
            str1 = "12.0001"
            TextBox1.AppendText(CDbl(str1).ToString("0.0###") & vbCrLf) ' 12.0001


    Regards Les, Livingston, Scotland

    Tuesday, April 23, 2019 1:41 PM