Reputation: 4938
Dim myStr As String = "38"
I want my result to be 38.000
...
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.
Upvotes: 10
Views: 75192
Reputation: 1725
Use FormatNumber:
Dim myStr As String = "38"
MsgBox(FormatNumber(CDbl(myStr), 3))
Dim myStr2 As String = "6.4"
MsgBox(FormatNumber(CDbl(myStr2), 3))
Upvotes: 17
Reputation: 20320
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.
Upvotes: 1
Reputation: 35706
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.
Upvotes: 4
Reputation: 7407
Take a look on "Standard Numeric Format Strings"
float value = 6.4f;
Console.WriteLine(value.ToString("N3", CultureInfo.InvariantCulture));
// Displays 6.400
Upvotes: 2