Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 196
  • Last Modified:

Convert number to string with leading spaces

// there's got to be an easier better way
string ValueStr;
if (Number < 10)
{
  ValueStr = "  " + Number.ToString();
}
else if (Number < 100)
{
  ValueStr = " " + Number.ToString();
}
else if (Number < 1000)
{
  ValueStr = Number.ToString();
}
else
{
  ValueStr = "---";
}

Open in new window

0
deleyd
Asked:
deleyd
1 Solution
 
käµfm³d 👽Commented:
You can do something like this:

string ValueStr = string.Format("{0,3:0}", Number);

Open in new window


Where "{0}" is the placeholder for the first parameter following the format string (in this case, Number), ",3" means right justify the value and make the field a width of 3, and ":0" means format the value as a number, where there is at least one zero. You could also do:

string ValueStr = string.Format("{0,3:##0}", Number);

Open in new window


which does the same thing, and essentially means the same thing, but is more visually indicative of what is going on. The hashes ( # ) mean optional values.
0

Featured Post

Efficient way to get backups off site to Azure

This user guide provides instructions on how to deploy and configure both a StoneFly Scale Out NAS Enterprise Cloud Drive virtual machine and Veeam Cloud Connect in the Microsoft Azure Cloud.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now