Reputation: 1034
Given a decimal value, how can I add a leading zero in a string only when a value is less than 1?
Eg.
.20 -> "0.20" - Add a leading 0
1.20 -> "1.20" - Value remains the same
The value before the decimal place could be of any length and the value after the decimal place will only be 2 digits ie. currency. Is this achievable with String.Format()? Or should I rely on a basic if statement?
The String.Format() documentation is rather confusing to me.
I've checked several other questions/answers and can't seem to find what I'm looking for.
EDIT: As mentioned by several answers, this kind of leading zero addition should be the default behavior of the ToString() method called on a value. For whatever reason, that isn't happening in my case, so The String.Format() is necessary in my case.
Upvotes: 2
Views: 2944
Reputation: 718
All the other prior answers would be the preferred way to do what you're attempting. But here is an alternative to using string format specifiers.
var valStrVersion = ((val < 1.0M) ? "0" + val.ToString() : val.ToString());
And then you could whatever it is you need to do with it. Convert it back, print it out, whatever. Are you appending M to your decimal value when you declare it? decimal dec = 0.15M;
?
Upvotes: 1
Reputation: 5189
What you are asking for is actually the default behavior of ToString()
for a decimal type. You dont need String.Format()
.
decimal d = .20M;
string s = d.ToString();
Console.WriteLine(s);
Upvotes: 2
Reputation: 727047
If you use zero before a dot in the format string, you would get the desired effect:
string.Format("{0:0.00}", currency);
or using C# 6 syntax
$"{currency:0.00}"
Note that .NET also provides a generic format specifier for formatting currency, which takes care of leading zero as well:
$"{currency:C}"
Upvotes: 2
Reputation: 3110
It is possible with string.format():
string.Format("{0:0.00}", 0.2) // 0.20
string.Format("{0:0.00}", 1.20) // 1.20
You can also use ToString() on the variables themselves:
var d1 = 0.2;
var d2 = 1.20;
Console.WriteLine(d1.ToString("0.00")); // 0.20
Console.WriteLine(d2.ToString("0.00")); // 1.20
Upvotes: 6