Alex
Alex

Reputation: 4938

String 3 decimal places

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.

Upvotes: 10

Views: 75192

Answers (4)

GJKH
GJKH

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

Tony Hopkinson
Tony Hopkinson

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

Jodrell
Jodrell

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

giacomelli
giacomelli

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

Related Questions