Solved

Convert number to string with leading spaces

Posted on 2011-09-29
1
183 Views
Last Modified: 2013-12-17
// 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
Comment
Question by:deleyd
1 Comment
 
LVL 75

Accepted Solution

by:
käµfm³d   👽 earned 500 total points
ID: 36818647
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

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
SqlDataBase 7 48
converto datetime always changes format 9 37
InputLanguage 1 26
SQL Help 27 45
This document covers how to connect to SQL Server and browse its contents.  It is meant for those new to Visual Studio and/or working with Microsoft SQL Server.  It is not a guide to building SQL Server database connections in your code.  This is mo…
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…

773 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question