Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add 0 before number if < 10

This is my code:

string Unreadz = "0";
while (true)
{
    Unreadz = CheckMail();       
    if (!Unreadz.Equals("0")) port.Write("m");
    else port.Write("n");
}

If Unreadz is less than 10, I want to add a 0 before it, before port.write.

This is what I have tried:

if (Unreadz < 10) port.Write("0" + Unreadz);
else port.Write("" + Unreadz);

but it doesn't work because Unreadz is a string.

like image 897
Csharpz Avatar asked Aug 22 '11 13:08

Csharpz


People also ask

Why do we put 0 before a number?

Leading zeros can also be used to prevent fraud by filling in character positions that might normally be empty. For example, adding leading zeros to the amount of a check (or similar financial document) makes it more difficult for fraudsters to alter the amount of the check before presenting it for payment.

How do I keep a leading zero in Excel?

Use the "0"# format when you want to display one leading zero. When you use this format, the numbers that you type and the numbers that Microsoft Excel displays are listed in the following table. Example 2: Use the "000"# format when you want to display three leading zeros.

How do you add leading zeros in Java?

The format() method of String class in Java 5 is the first choice. You just need to add "%03d" to add 3 leading zeros in an Integer. Formatting instruction to String starts with "%" and 0 is the character which is used in padding.


1 Answers

This should work:

port.Write(Unreadz.ToString().PadLeft(2, '0'));
like image 121
Shadow Wizard Hates Omicron Avatar answered Sep 26 '22 08:09

Shadow Wizard Hates Omicron