Trying to pad decimal number with leading spaces - c#

for (int iCount = 0; iCount < oForm.LineItems.Count; iCount++)
{
// cartDetails is a stringbuilder here.
cartDetails.Append(String.Format("{0:0}", oForm.LineItems[iCount].Quantity));
cartDetails.Append(String.Format("{0:0.00}", oForm.LineItems[iCount].Price));
cartDetails.Append(String.Format("{0:0.00}", oForm.LineItems[iCount].ExtendedPrice));
//cartDetails.Append(string.Format("{0,10:#,##0.00}", oForm.LineItems[iCount].Price) + "</TD><TD>");
//cartDetails.Append(string.Format("{0,10:#,##0.00}", oForm.LineItems[iCount].ExtendedPrice) + "</TD><TD>");
//cartDetails.Append(String.Format("{0}", oForm.LineItems[iCount].Quantity).PadLeft(4)+ "</TD><TD>");
//cartDetails.Append(String.Format("{0:0.00}", oForm.LineItems[iCount].Price).PadLeft(8) + "</TD><TD>");
I have pastd the source code I am using. I add qty, price, extendedprice and all are decimal columns. All I am looking to do is to pad left with leading spaces. Decimal rounding to 2 digits seems to be happening.
Those commented lines above are some of the other options I have tried.
Currently if qty has values such as 4 and 40, they don't get aligned when I print them in a table. Same with price.
CAn someone please suggest what am I doing here?
Update1: Tried Lucas suggestion, but it is not working. Here is what I am geting.
cartDetails.Append(String.Format("{0:0,10}", oForm.LineItems[iCount].Quantity));
When I try the above, it shows 10 for every line irrespective of the value in oForm.LineItems[iCount].Quantity.
And if I change
String.Format("{0:0,4}", it shows 04 for all the records

You can use AppendFormat method instead of appending formatted string.
Also correct format will be {index,padding:format}. And consider to use foreach instead of for:
foreach (var lineItem in oForm.LineItems)
{
cartDetails.AppendFormat("{0,4:0}", lineItem.Quantity);
cartDetails.AppendFormat("{0,10:0.00}", lineItem.Price);
// etc
}

Remark: This is for alignemend in caracter based representation such as text files
Have a look at the last section in composite formatting (MSDN).
First format the number as desired and the pad the result
cartDetails.AppendFormat("{0,4}", // padding with spaces
String.Format("{0:0}", oForm.LineItems[iCount].Quantity)); // format number
Addtition: If you want to position your data in a html table you should use css (or inline styles)
<td class="right">This is right aligned</td>
with css
.right { text-align: right; }
or inlined:
<td style="text-align: right">This is right aligned</td>

Related

Tail truncation for each 2 formatted text spans

In our mobile app we have 2 DateTime values separated by a '-', e.g. "2022/07/13 00:00 - 2023/07/13 23:59". In landscape mode we achieve the formatting desired by using formatted text, spans and maxlines properties. In portrait mode however, we still desire displaying the values on 2 lines, but each span must be truncated with tail truncation. E.g.
20/07/2021 ...
20/07/2022 ...
I've tried something like and variations of:
control.MaxLines = 2;
control.LineBreakMode = LineBreakMode.TailTruncation;
control.FormattedText.Spans.Add(new Span { Text = dates[0] + seperator });
control.FormattedText.Spans.Add(new Span { Text = System.Environment.NewLine });
control.FormattedText.Spans.Add(new Span { Text = dates[1].TrimStart() });
It's worth mentioning that this logic should be functional for different widths of the custom control being used (based off of a label). Is there something small I'm missing or is this not possible using formatted text?
Thanks in advance!

c# read the value of a changing Progressbar in webbrowser

I am kinda new to c# (spent my time in delphi before) and I am having trouble finding this out:
the Html code of the website is this:
<div class="progress-bar progress-bar-danger" id="counter" style="width: 10.%; overflow: hidden;"></div>
I am trying to figure out sth like this:
var CheckValue = webBrowser1.Document.GetElementById("counter"); if (counter.style.width > 70%) { //code }
So basically what im trying to do is:
I want to check if the width of the progressbar on the website ist filled by more than 70% and if it is it shall execute a code but if it isnt it shall try again after a few seconds.
If you need any more information just tell me!
Thanks
You can use CheckValue.Style, which will return a string containing the style. Then you can use Regex to find what you are looking for.
You want your regex to match the digits between the width: and the .%. You can use this for that:
width: ([0-9]+(\.[0-9]+)?)\.?%
This will match every string starting with width: and ending with % with the possibility of a . before the %, with at least 1 character between 0 and 9.
You can use this code to get this value:
var checkValue = webBrowser1.Document.GetElementById("counter");
Regex regex = new Regex("width: ([0-9]+(\\.[0-9]+)?)\\.?%");
Match match = regex.Match(checkValue.Style);
// Check if match found
if (match.Groups.Count > 1)
{
String s = match.Groups[1].ToString();
int width = (int)Convert.ToDouble(s);
}

Export from datagridview to *.txt file only first 20 cell's letters

I'm using this code to export from datagridview to *.txt file
TextWriter sw = new StreamWriter(#"C:\fiscal.txt");
int rowcount = dataGridView1.Rows.Count;
for (int i = 0; i < rowcount - 1; i++)
{
sw.Write("{0,-20}", dataGridView1.Rows[i].Cells[0].Value.ToString());
}
sw.Close();
But if my datagridview's cell is bigger than 20 letters i want to delete rest of them. And to export only my first 20 letters.
Hope Substring() will help you in following way: include the snippet inside the for
string tempString = dataGridView1.Rows[i].Cells[0].Value.ToString();
if(tempString.Length>20)
tempString=tempString.Substring(0,20);
else
{
tempString = tempString.PadRight(20); //use this if you need space after the word
tempString = tempString.PadLeft(20); //use this if you need space before the word
}
sw.Write(tempString);
Update: as per op's comment:
You can use Padding to append an empty string with your actual string. C# offers two padding options such as right padding and left padding.
PadRight adds spaces to the right of strings. PadLeft meanwhile adds
to the left. These methods make the text easier to read. Padding a string
adds whitespace or other characters to the beginning or end. Any
character can be used for padding.

Insert space between numbers in Textbox

Hello and Thanks for reading.
I have this TextBox where a user can type in his/her Phone number.
<asp:TextBox runat="server" ID="txtPhone" CssClass="TicketField FieldWidthH txtboxStyle" />
If the user types 12345678 I would like it to auto "show" 12 34 56 78 so there is a space after each 2 numbers.
Here is my C# code:
if (IsPostBack) {
if (!string.IsNullOrEmpty(txtPhone.Text)) {
// Check if the value contains any non-numeric values and strip them out
string cleanedUpTextBoxValue = Regex.Replace(txtPhone.Text, #"^\d{6}$", "");
// Parse your number as an integer from your TextBox (after cleaning it up)
Int64 yourIntegerTextBoxValue = Int64.Parse(cleanedUpTextBoxValue);
// Format your number as a string
string formattedResult = yourIntegerTextBoxValue.ToString("## ## ## ##");
// Output the result into your TextBox
txtPhone.Text = formattedResult;
}
}
I also tried string cleanedUpTextBoxValue = Regex.Replace(txtPhone.Text, "[^\d]", "");
But then I type in the Textbox I still only displays the numbers as 12345678.
What am i doing wrong?
Thanks for your time
I'd generally recommend using JavaScript for this if possible, but if you want a C# solution, you can use this to strip out non-digit characters:
string text = Regex.Replace(txtPhone.Text, #"\D", "");
And then this to insert spaces around each pair of digits:
text = Regex.Replace(text, #"\d\d(?!$)", "$0 ");
txtPhone.Text = text;
If implemented in JavaScript, it would look a little bit like this:
text = text.replace(/\D/g, '').replace(/(\d\d)(?!$)/g, '$1 ')
Use the Insert method of string.
string phone = txtPhone.Text; // or your cleaned-up string
phone = phone.Insert(2, " ");
txtPhone.Text = phone;
You can put a loop in there to get spaces between every other digit as needed. Looping over the length of the string, starting from the end, is probably the easiest. Check the length of the string to determine your starting position (i.e., the last character or next to last). What happens if the user enters an odd number of digits?

How to check if a position in a string is empty in c#

I have strings with space seperated values and I would like to pick up from a certain index to another and save it in a variable. The strings are as follows:
John Doe Villa Grazia 323334I
I managed to store the id card (3rd column) by using:
if (line.length > 39)
{
idCard = line.Substring(39, 46);
}
However, if I store the name and address (1st and 2nd columns) with Substring there will be empty spaces since they are not of the same length (unlike the id cards). How can I store these 2 values and removing the unneccasry spaces BUT allowing the spaces between name and surname?
Try this:
string line = " John Doe Villa Grazia 323334I";
string name = line.Substring(02, 16).Trim();
string address = line.Substring(18, 23).Trim();
string id = line.Substring(41, 07).Trim();
var values = line.Split(' ');
string name = values[0] + " " + values[1];
string idCard = values[4];
It will be impossible to do without database lookups on names if there aren't spaces for sure in the previous columns.
Are these actually space separated or are they really fix width columns?
By that I mean do the "columns" start at the same index into the string in each case - from the way you're describing the data is sounds like the later i.e. the ID column is always column 39 for 7 characters.
In which case you need to a) pull the columns using the appropriate substring calls as you're already doing and then, use "string ".Trim() to cut off the spaces.
If the rows, are, as it seems fixed with then you don't want to use Split at all.
How can you even get the ID like that, when everything in front of it is of variable length? If that was used for my name, "David Hedlund 323334I", the ID would start at pos 14, not 39.
Try this more dynamic approach:
var name = str.Substring(0, str.LastIndexOf(" "));
var id = str.Substring(str.LastIndexOf(" ")+1);
Looks like your parsing strategy will cause you a lot of trouble. You shouldn't count on the string's size in order to parse it.
Why not save the data in CSV format (John Doe, Villa Grazia, 323334I)?
that way, you can assume that each "column" will be separated by a comma which will make your parsing efforts easier.
Possible "DOH!" question but are you sure they are spaces and not Tabs? Looks like it "could" be a tab seperated file?
Also for browie points you should use String.Empty instead of ' ' for comparisons, its more localisation and memory friendly apparently.
The first approach would be - as already mentioned - a CSV-like structure with a defined token as the field separator.
The second one would be fixed field lengths so you know the first column goes from char 1 to char 20, the second column from char 21 to char 30, and so on.
There is nothing bad about this concept besides that the human readability may be poor if the columns are filled up to their maximum so no spaces remain between them.
You could write a helper function or class which knows about the field lengths and provides an index-based, fault-tolerant access to the particular column. This function would extract the particular string parts and remove the leading and trailing spaces but leave the spaces in between as they are.
If your values have fixed width, best not split it but use the right indexes in your array.
const string input = "John Doe Villa Grazia 323334I";
var name = input.Substring(0, 15).TrimEnd();
var place = input.Substring(16, 38).TrimEnd();
var cardId = input.Substring(39).TrimEnd();
Assuming your values cannot contain two sequential spaces in them we can maybe use " " (double space" as a separator?
The following code will split your string based on the double space
const string input = "John Doe Villa Grazia 323334I";
var entries = input.Split(new[]{" "}, StringSplitOptions.RemoveEmptyEntries)
.Select(s=>s.Trim()).ToArray();
string name = entries[0];
string place = entries[1];
string idCard = entries[2];

Categories