String 3 decimal places

70,995

Solution 1

Use FormatNumber:

Dim myStr As String = "38"
MsgBox(FormatNumber(CDbl(myStr), 3))

Dim myStr2 As String = "6.4"
MsgBox(FormatNumber(CDbl(myStr2), 3))

Solution 2

So if you have

Dim thirtyEight = "38"
Dim sixPointFour = "6.4"

Then, the best way to parse those to a numeric type is, Double.Parse or Int32.Parse, you should keep your data typed until you want to display it to the user.

Then, if you want to format a string with 3 decimal places, do somthing like String.Format("{0:N3}", value).

So, if you want a quick hack for the problem,

Dim yourString = String.Format("{0:N3}", Double.Parse("38"))

would do.

Solution 3

Take a look on "Standard Numeric Format Strings"

float value = 6.4f;
Console.WriteLine(value.ToString("N3", CultureInfo.InvariantCulture));
// Displays 6.400

Solution 4

In pseudo code

decpoint = Value.IndexOf(".");
If decpoint < 0 
  return String.Concat(value,".000")
else
  return value.PadRight(3 - (value.length - decpoint),"0")

If it's string keep it as a string. If it's a number pass it as one.

Share:
70,995
Alex
Author by

Alex

Updated on July 13, 2022

Comments

  • Alex
    Alex almost 2 years

    Example 1

    Dim myStr As String = "38"
    

    I want my result to be 38.000 ...


    Example 2

    myStr = "6.4"
    

    I want my result to be 6.400


    What is the best method to achieve this? I want to format a string variable with atleast three decimal places.

    • Idle_Mind
      Idle_Mind about 11 years
      Are you really starting with a String value?
    • Tim
      Tim about 11 years
      Probably not what you intended, but if it's simply a string than Dim myStr As String = "38.000" and Dim myStr As String = "6.4000" would work. I think you're actually asking how to convert a string representation of a number to a decimal, yes?
    • Jodrell
      Jodrell about 11 years
      the result of assigning a String literal to a variable?
    • Alex
      Alex about 11 years
      Editted so it makes more sense
    • Tony Hopkinson
      Tony Hopkinson about 11 years
      only makes sense if Fred.000 is an acceptable output...
  • Jodrell
    Jodrell about 11 years
    or, simpler Console.WriteLine("{0:N3}", value)
  • Alex
    Alex about 11 years
    But my value is initially a string. Not a decimal. So when I try to format it using ToString() I get a System.IFormatProvider error
  • Tony Hopkinson
    Tony Hopkinson about 11 years
    Just be careful. The assumption that the value is a number in an acceptable format is iffy. 0.0001, would be a possible issue as well.
  • GJKH
    GJKH about 11 years
    True, you really shouldn't be storing numbers as strings, you should convert them to strings when needed.