Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 
like image 618
Jakob Gade Avatar asked Nov 28 '11 08:11

Jakob Gade


People also ask

How do you convert a decimal to a string?

To convert a Decimal value to its string representation using a specified culture and a specific format string, call the Decimal. ToString(String, IFormatProvider) method.

How do you format a string to show two decimal places?

String strDouble = String. format("%. 2f", 1.23456); This will format the floating point number 1.23456 up-to 2 decimal places, because we have used two after decimal point in formatting instruction %.

How do you put a space in a string format?

Use the String. format() method to pad the string with spaces on left and right, and then replace these spaces with the given character using String. replace() method. For left padding, the syntax to use the String.

Does string format round?

If the value to be formatted has more than the specified or default number of decimal places, the fractional value is rounded in the result string. If the value to the right of the number of specified decimal places is 5 or greater, the last digit in the result string is rounded away from zero.


1 Answers

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" 
like image 197
nemesv Avatar answered Sep 24 '22 12:09

nemesv