jprbest
jprbest

Reputation: 737

How do I format numbers differently based on their value in C#?

I have an integer that I will store in a string according to the following rules:

  1. If the number is less then 10, then it should have a 0 before it.
  2. If it larger than 10, store it without a leading 0.

How can I do this in C#?

Upvotes: 3

Views: 1535

Answers (6)

Murian
Murian

Reputation: 91

You can use:

String.Format("{0:D2}", myInt);

The ":D2" tells String.Format to pad the number to at least two digits by prepending zeros. If it's longer than two digits it won't pad anything.

Upvotes: 3

pmartin
pmartin

Reputation: 2741

This site is a great reference: http://blog.stevex.net/string-formatting-in-csharp/

For your problem, you can also use this: String.Format("{0:0#}", <yourIntegerVariable>)

Upvotes: 2

sourcenouveau
sourcenouveau

Reputation: 30504

You can find information on formatting numbers on MSDN at:

One answer to your question is:

string formatted = myNumber.ToString("00");

Upvotes: 2

WraithNath
WraithNath

Reputation: 18013

int i = 8;

string s = String.Format("{0:00}", i);

00 represents 2 digits 00.00 would represend 2 digits and 2 decimals

Upvotes: 0

SLaks
SLaks

Reputation: 887275

If you already have the string, you can write

str = str.PadLeft(2, '0');

Note that you might be looking for

string str = new DateTime(1,1,1, 12,34,56).ToShortTimeString();

This returns 12:34 PM, and can be customized using format strings.

Upvotes: 1

Klaus Byskov Pedersen
Klaus Byskov Pedersen

Reputation: 120917

You can use ToString with a format string:

var i = 6;
var stringRepresentation = i.ToString("d2");

Upvotes: 7

Related Questions