2

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.

4 Answers 4

6

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
2

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}"
2

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);
5
  • Not sure why, but ToString() was giving me ".20", which is why I wanted to look for another way. Jun 24, 2016 at 17:49
  • What data type are you using for your number? Jun 24, 2016 at 17:50
  • The data type is decimal Jun 24, 2016 at 17:52
  • Strange, I know. I've tried multiple online C# test environments and they give me "0.20", but for whatever reason, my program is shooting ".20" at me. Jun 24, 2016 at 17:54
  • Ah it must be a culture related. My CultureInfo.CurrentCulture is en-US Jun 24, 2016 at 17:57
1

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;?

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.