Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to align floating point numbers in C# (left padding)

I have the following floating point numbers, all with 2 decimal places:

2.47
57.83
93.92
119.20

I want to output these numbers as follows:

  2.47
 57.83
 93.92
119.20

How can I achieve that in C#, if the font is not monospaced?

Edit:

Or is there any invisible character that occupies the same amount of horizontal space as a digit?

like image 508
sergej Avatar asked Nov 24 '25 02:11

sergej


2 Answers

Try string.Format("{0,6:F2}", number).

Since C# 6.0 from 2015, you can write $"{number,6:F2}" instead.

like image 111
Jeppe Stig Nielsen Avatar answered Nov 26 '25 16:11

Jeppe Stig Nielsen


I've never used Gtk# before, but a quick Google search revealed this.

label.Justify = Justification.Right;

This is a much simpler and more reliable strategy than trying to manipulate the string to the proper width.

like image 24
p.s.w.g Avatar answered Nov 26 '25 16:11

p.s.w.g