Matt Wilko
Matt Wilko

Reputation: 27322

Using String.Format to specify the decimal places at runtime

I want to use String.Format to specify the number of decimal places to display where the number of decimal places may change at runtime.

Normally I would do this:

Dim d As Decimal = 1.23456D
Debug.WriteLine(String.Format("My number to 2 decimal places is {0:f2}", d))

What I want to do is this:

Dim d As Decimal = 1.23456D
Dim places as integer = 2
Debug.WriteLine(String.Format("My number to {0} decimal places is {1:f" + places.ToString + "}", places, d))

But without having to concat the string. Is there any way to do this?

Upvotes: 2

Views: 648

Answers (2)

You could create an extension to format the value to string with the number of places desired. It hides the details of the implementation in a function but makes it as easy to use as ToString:

<Extension()>
Public Function ToStringPlaces(value As Decimal, places As Integer) As String
    ' ToDo: error checking
    Return String.Format(value.ToString("f" & places.ToString))
End Function

Test:

Private pi As Decimal = 22/7
'...
Label1.Text = pi.ToStringPlaces(3)

==> 3.142

Upvotes: 1

prem
prem

Reputation: 3538

Without concatenating the string you can do it like this

 Dim d As Decimal = 1.23456D
 Dim places As Integer = 2
 Debug.WriteLine(String.Format("My number to {0} decimal places is {1}", places, Decimal.Round(d, places)))

Upvotes: 3

Related Questions