'Format decimal value to string with leading spaces

How do I format a decimal value to a string with a single digit after the comma/dot and leading spaces for values less than 100?

For example, a decimal value of 12.3456 should be output as " 12.3" with single leading space. 10.011 would be " 10.0". 123.123 is "123.1"

I'm looking for a solution, that works with standard/custom string formatting, i.e.

decimal value = 12.345456;
Console.Write("{0:magic}", value); // 'magic' would be a fancy pattern.


Solution 1:[1]

Another one with string interpolation (C# 6+):

double x = 123.456;
$"{x,15:N4}"// left pad with spaces to 15 total, numeric with fixed 4 decimals

Expression returns: " 123.4560"

Solution 2:[2]

value.ToString("N1");

Change the number for more decimal places.

EDIT: Missed the padding bit

value.ToString("N1").PadLeft(1);

Solution 3:[3]

Many good answers, but this is what I use the most (c# 6+):

Debug.WriteLine($"{height,6:##0.00}");
//if height is 1.23 =>   "  1.23"
//if height is 0.23 =>   "  0.23"
//if height is 123.23 => "123.23"

Solution 4:[4]

All above solution will do rounding of decimal, just in case somebody is searching for solution without rounding

decimal dValue = Math.Truncate(1.199999 * 100) / 100;
dValue .ToString("0.00");//output 1.99

Solution 5:[5]

Note the "." could be a "," depending on Region settings, when using string.Format.

string.Format("{0,5:###.0}", 0.9)     // Output  "   .9"
string.Format("{0,5:##0.0}", 0.9)     // Output  "  0.9"

I ended up using this:

string String_SetRPM = $"{Values_SetRPM,5:##0}";
// Prints for example "    0", " 3000", and "24000"

string String_Amps = $"{(Values_Amps * 0.1),5:##0.0}";
// Print for example "  2.3"

Thanks a lot!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Freek Wiekmeijer
Solution 2 Taz
Solution 3 Brian Hong
Solution 4
Solution 5