Line up Characters - c#

I have a combobox made up of two numbers; inches and millimetres. At the moment it is looking hideous. I am wondering if some of the gurus here have anyway of lining the character '|' or at least make it nicer?
A bit of background info, the number inches and millimetres are separate strings which I append together like so:
Size(in) + " (In) | " + Size(mm) + " (mm)"

Possibly the cleanest way would be to format every number to have 3 decimal places for at least inches. This still won't be perfect however since the letter font width won't be perfect, to fix that you'd need to use a monospaced font.
To format to 3dp you can use the following
String.Format("{0:f3}", Size(in)) + " (In) | " + Size(mm) + " (mm)"
Since you have some values that are 2 digits before the decimal you can always use PadLeft to align these, but again this doesn't always work well without a monospaced font..
String.Format("{0:f3}", Size(in)).PadLeft(5, ' ') // or (5, '0')

Use String.PadRight(i); and String.PadLeft(i); where i is a nr. of spaces to "fill":
Example:
// Just to simplify a little, create vars:
var inches = Size(in) + " (In) ";
var mm = " + Size(mm) + " (mm)";
var formatted = inches.PadRight(15) + "|" + mm.PadLeft(15);
Example of output using 15 for the padding value (obviously, you can adjust this as needed):
43 inches | 123 cm
445554 inches | 12345 cm

Related

How do I align text like columns in a treeview?

I have a TreeView where I want to arrange my data nicely.
I format my string like this:
string name = ItemName;
string current = ("Current: " + info.Current.ToString() + " " + identifier);
string maximum = ("Maximum: " + info.Max.ToString() + " " + identifier);
string minimum = ("Minimum: " + info.Min.ToString() + " " + identifier);
string output = string.Format("{0,-20}{1,-30}{2,-30}{3,-30}{4,-30}", name, current, maximum, minimum, average);
dataNode.Text = output;
When I write output to the console it prints it the way I want it, like this (values are off, but that's irrelevant):
Load Current: 9,23 % Maximum: 33,33 % Minimum: 6,06 % Average: 0 %
Temperature Current: 40 °C Maximum: 49 °C Minimum: 38 °C Average: 0 °C
Clock Current: 1200 Mhz Maximum: 2800,09 Mhz Minimum: 1200 Mhz Average: 0 Mhz
etc..
But when I print the exact same strings to my TreeView it shows it like this:
I followed the example on this page but that didn't work for me.
I guess it has something to do with the different nodes I use in my TreeView but I don't know how to properly align my data.
seems like you need to set monospaced font for TreeView.
here is a similar question with example of monospaced font (FontFamily.GenericMonospace):
C# .NET multiline TextBox with same-width characters
This is a perfect situation for .PadRight() or .PadLeft().
string output =
string.Format("{0}{1}{2}{3}{4}",
name.PadRight(20),
current.PadRight(30),
maximum.PadRight(30),
minimum.PadRight(30),
average.PadRight(30));
This code will ensure that the space taken up by each parameter is the same every time.
You can use other controls how alow to create columns like :
There are a number of sample controls to be found around the web:
TreeViewAdv for .Net
TreeView with Columns
ContainerListView and TreeListView
Try just to change font of treeView to use a
non-proportional font like "Courier" , "Consolas"

Cannot apply bit mask

I am making a horse programme. I have the horse face and wish to apply a bit mask. Only the horses eyes should be visible when it is wearing the bit mask. First I must convert the horses face to digital. For this I have a set of bits which include 0, 0, 0, and 1 for the face of the horse.
I am using C# and have broken the problem into parts:
Convert the horse's head to digital
Build a bit mask for it to wear
Put the bit mask on the horse
Convert the digital masked horse back
into graphics
At step 4 I expect only to see the horses eyes but I only see "0" which IS NOT EVEN A HORSE FACE.
Here is all of my code, please don't question my ASCII art it is not relevant to the question, besides it is a prototype the real program will have superior graphics.
//the head of the horse
string head = "# #" +
"########" +
"#O O#" +
"# #" +
"# #" +
"#= =#" +
" #====# " +
" #### ";
//digitize the horse into bits of binary
string binaryHead = head.Replace('#', '0').Replace('=', '0').Replace(' ', '0').Replace('O', '1');
long face = Convert.ToInt64(binaryHead, 2);
//make a bit mask with holes for the eyes
string mask = "11111111" +
"11111111" +
"10111101" +
"11111111" +
"11111111" +
"11111111" +
"11111111" +
"11111111";
//apply the bit mask using C#
long maskBits = Convert.ToInt64(mask, 2);
string eyesOnly = Convert.ToString(face & maskBits, 2);
//eyesOnly is "0"....WHAT??? It should be more than that. WHERE IS THE HORSE??
//It should look like this:
// "00000000" +
// "00000000" +
// "01000010" +
// "00000000" +
// "00000000" +
// "00000000" +
// "00000000" +
// "00000000";
I suspect something is wrong with the conversion, I have tried all kinds of things like converting to a byte array and formatting the string with spaces but with no luck. I am wondering if this problem might be NP-hard.
face and eyesOnly have no common 1-bits. maskBits leaves everything except for the eyes. Either swap 0 and 1, or use the ~ operator to flip maskBits. And give it a better name so that it is clear what it is a mask for: bitmaskForNotEyes.
I think the problem is -
string binaryHead = head.Replace('#', '0').Replace('=', '0').Replace(' ', '0').Replace('O', '1');
First, all '#' are changed to '0'.
Then all '=' are changed to '0'
All ' ' are changed to '0'.
Finally the eyes to '1'
So, after the conversion the head looks like this -
string head = "00000000" +
"00000000" +
"01000010" +
"00000000" +
"00000000" +
"00000000" +
" 000000 " +
" 0000 ";
Now you are doing & with it -
string mask = "11111111" +
"11111111" +
"10111101" +
"11111111" +
"11111111" +
"11111111" +
"11111111" +
"11111111";
so the output is obviously 0.

Format custom numeric string with fixed character count

I need to convert any number in a fixed format with a fixed amount of characters. Means 1500 and -1.5 or 0.025 need to have the same length. I also have to give the format in this form: Format = "{???}";
When i type Format = "{0000}"; i can limit 1500 to "1500", but -1.5 -> "-0001.5" means i have too much numbers after the point.
Negative sign place can be done with Format = "{ 0.0;-0.0; 0.0}".
How can i fix the count of the numbers for different numbers?
The length of the string doesn't matter, the most important is the equal length.
Examples:
1500 -> " 1500.000" or " 1500"
-1500 -> "-1500.000" or "- 1500" or " -1500"
1.5 -> " 1.500" or " 1.5"
-0.25-> " -0.250" or "- 0.25"
0.00005 -> " 0.000" or " 0"
150000-> " 150000.0" or " 150000"
15000000 " 15000000"
Edit:
I want to Format an y-Axis of a Chart. I can't use something like value.ToString("???") i need to use chartArea.AxisY.LabelStyle.Format = "{???}";
Why don't use formatting? "F3" forces 3 digits after decimal point and PadLeft ensures the overall length
Double value = 1500.0;
// 3 digits after decimal point, 9 characters length
String result = value.ToString("F3").PadLeft(9, ' ');
0 -> 0.000
1500.0 -> 1500.000
-1500.0 -> -1500.000
-0.25 -> -0.250
Another (similar) possibility is String.Format:
Double value = 1500.0;
// Put value at place {0} with format "F4" aligned to right up to 9 symbols
String result = String.Format("{0:9,F4}", value);
Try it > result = Math.Round(yourValue, 3);
Check full reference here !
you cannot achieve this by a simple format function
string result = string.Empty;
var array = dec.ToString().Split('.');
if (dec > 0)
{
result = array[0].PadLeft(9).Remove(0, 9);
if (array.Count() > 1)
{
result += '.' + array[1].PadRight(3).Remove(3);
}
}
else
{
result = "-"+array[0].PadLeft(9).Remove(0, 9);
if (array.Count() > 1)
{
result += '.' + array[1].PadRight(3).Remove(3);
}
}

String Format wrong format for % [duplicate]

This question already has answers here:
How can I use a percent % in FormatString without it multiplying by 100?
(4 answers)
Closed 9 years ago.
I want to format an Axis in a Chart. For this i have following line:
chart.ChartAreas[series.Name].AxisY.LabelStyle.Format =
"{0.# " + unit + ";-0.# " + unit + ";0 " + unit + "}";
Example for unit = "Joule": Format = "{0.# Joule;-0.# Joule;0 Joule"}
It brings me a good result (e.g. 1.5 -> "1.5 Joule", -1.4 -> "-1.4 Joule").
But if unit = "%" the values are multiplicated by 100. Means 5 -> "500%", 1.3 -> "130%"... and that's wrong. Also some inputs like " %" (with a variable spaces in the string), "_%", "‰" multiplicate the numbers.
Is there a way to show a percent number and prevent this effect?
Please note that i have to use the Format in this form Format = "???"; and i don't want to manipulate any DataPoints (like every DataPoint / 100).
You can put literal characters in quotes to avoid them being interpreted as format codes:
chart.ChartAreas[series.Name].AxisY.LabelStyle.Format =
"{0.# '" + unit + "';-0.# '" + unit + "';0 '" + unit + "'}";
Escape the percentage sign.
unit = #"\%";
or
unit = "\\%;

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.
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"
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"
value.ToString("N1");
Change the number for more decimal places.
EDIT: Missed the padding bit
value.ToString("N1").PadLeft(1);
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"
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
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!

Categories

Resources