问题
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.
回答1:
Use FormatNumber:
Dim myStr As String = "38"
MsgBox(FormatNumber(CDbl(myStr), 3))
Dim myStr2 As String = "6.4"
MsgBox(FormatNumber(CDbl(myStr2), 3))
回答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.
回答3:
Take a look on "Standard Numeric Format Strings"
float value = 6.4f;
Console.WriteLine(value.ToString("N3", CultureInfo.InvariantCulture));
// Displays 6.400
回答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.
来源:https://stackoverflow.com/questions/16465321/string-3-decimal-places