Format decimal value to string with leading spaces

C#.Netvb.netString Formatting

C# Problem Overview


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.

C# Solutions


Solution 1 - C#

This pattern {0,5:###.0} should work:

string.Format("{0,5:###.0}", 12.3456) //Output  " 12.3"
string.Format("{0,5:###.0}", 10.011)  //Output  " 10.0" 
string.Format("{0,5:###.0}", 123.123) //Output  "123.1"
string.Format("{0,5:###.0}", 1.123)   //Output  "  1.1"
string.Format("{0,5:###.0}", 1234.123)//Output "1234.1"

Solution 2 - C#

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 3 - C#

value.ToString("N1");

Change the number for more decimal places.

EDIT: Missed the padding bit

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

Solution 4 - C#

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 5 - C#

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 6 - C#

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!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJakob GadeView Question on Stackoverflow
Solution 1 - C#nemesvView Answer on Stackoverflow
Solution 2 - C#Freek WiekmeijerView Answer on Stackoverflow
Solution 3 - C#TazView Answer on Stackoverflow
Solution 4 - C#Brian HongView Answer on Stackoverflow
Solution 5 - C#Anshul NigamView Answer on Stackoverflow
Solution 6 - C#JackView Answer on Stackoverflow