I am receiving a csv string that I need to display in a .Net6.0 wpf ListView
. I'm processing thousands of strings per second, and would like a quick way to truncate a string after the decimal for six of the values in the string. I know that I can convert to a number, but this seems bulky, especially since I would have to convert back to string for display. Here is my function:
public void AddComponent(string component)
{
Component newcomp = new Component();
string[] items = component.Split(',');
newcomp.Time = items[0].Substring(items[0].IndexOf(':') + 1);
newcomp.CompId = items[1];
newcomp.Range = items[2].Substring(0, items[2].IndexOf('.') + 3);
newcomp.Diameter = items[3].Substring(0, items[3].IndexOf('.') + 3);
newcomp.Radius = items[4].Substring(0, items[4].IndexOf('.') + 3);
newcomp.Height = items[5];
newcomp.Validity = EnumExtensions.GetDescription((ComponentValidity)(ushort.Parse(items[6])));
newcomp.Value = items[7];
newcomp.RCS = items[8];
newcomp.Status = EnumExtensions.GetDescription((ComponentStatus)ushort.Parse(items[9].Substring(0, 1)));
newcomp.Confidence = EnumExtensions.GetDescription((ComponentConfidence)ushort.Parse(items[9].Substring(3, 1)));
newcomp.MNF = items[10].Substring(0, items[10].IndexOf('.') + 3);
newcomp.Group = items[11];
newcomp.Classification = EnumExtensions.GetDescription((ComponentClassification)(ushort.Parse(items[12])));
newcomp.Serial = items[13];
newcomp.ShelfNumber = items[14].Substring(0, items[14].IndexOf('.') + 3);
newcomp.HYT = items[15].Substring(0, items[15].IndexOf('.') + 3);
Components.Add(newcomp);
}
The main ones I'm concerned about are the six that do this:
items[x].Substring(0, items[x].IndexOf('.') + 3);
These numbers can look like:
34.2
34.24
34.2456
76765.2232
I want the end result to be
34.2
34.24
34.24
76765.22
And of course the problem is the + 3
on the end of the line because sometimes there aren't enough characters to fill that out.
I'm already parsing some of the items to get the enum values, so I would rather not convert these strings to a decimal and back again. Is there an easy one-liner that might accomplish this?