formatting and aligning numbers of string

  • Thread starter Ralf Steinstraesser
  • Start date
R

Ralf Steinstraesser

Hi,

I am looking into formatting a double as as string. My starting point
therefor are the various capabilities of Excel to format numerical values.

One of the really nice things about formatting values in Excel the
possibility of aligning numbers in columns. If you use "_($.00_);($.00)" as a
custom format string, positive and negative values would perfectly align.
($2.50)
$2.50

Is there any formatting mechanism in the .NET framework which allows
vertical alignment of this example. I have tried with String.Format,
double.ToString using custom format strings and NumberFormatInfo, but didn't
get the result I wanted. This occurs when using fonts, which do not have
equally spaced characters.

Thanks for any advice.
 
G

Göran Andersson

Ralf said:
Hi,

I am looking into formatting a double as as string. My starting point
therefor are the various capabilities of Excel to format numerical values.

One of the really nice things about formatting values in Excel the
possibility of aligning numbers in columns. If you use "_($.00_);($.00)" as a
custom format string, positive and negative values would perfectly align.
($2.50)
$2.50

Is there any formatting mechanism in the .NET framework which allows
vertical

horisontal ;)
alignment of this example. I have tried with String.Format,
double.ToString using custom format strings and NumberFormatInfo, but didn't
get the result I wanted. This occurs when using fonts, which do not have
equally spaced characters.

You can use string.Format to left or right align a value:

string.Format("{0:0.00,5} {0:0.00,-5}", num)

If you display the string using a proportional font, you have to replace
the spaces with figure spaces:

string.Format("{0:0.00,5} {0:0.00,-5}", num).Replace(' ', '\u2007')

A figure space is a unicode character that is the same width as a digit.
In most fonts, even proportional fonts, the digits are all the same
width to allow for numbers to be aligned neatly in columns.
 
R

Ralf Steinstraesser

Hello Göran,

thanks for the tip with the figure space, which I didn't know about. Sounds
like this is going to solve my problem.

Best regards
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top