Numeric Format

jswota

Well-known member
Joined
Feb 23, 2009
Messages
49
Programming Experience
Beginner
Hi,
Does anyone now how i can format a number to only show decimal places if needed?

For instance...

string.format("{0:SomeFormat}", 26.9) = "26.9"

and...

string.format("{0:SomeFormat}", 26.0) = "26" 'Drop decimal for whole numbers


Thanks,
Joel
 
Use the ToString() method with formatting:

VB.NET:
Dim num As Double = 23.456
		MessageBox.Show(num.ToString("0"))
		MessageBox.Show(num.ToString("0.0"))


or for a Console app:

VB.NET:
Dim num As Double = 23.456
		Console.WriteLine(num.ToString("0"))
		Console.WriteLine(num.ToString("0.0"))
 
Use the ToString() method with formatting:
Using String.Format or ToString is not the issue here, they have same functionality, though ToString is simpler when converting a single value. Also, the zero-placeholder can't be used to solve this problem, as I said, the digit-placeholder must be used. The article I linked to explains the usage for all custom numeric format strings and has lots of accompanying code samples.
 
Back
Top