I have a numeric string like this 2223,00. I would like to transform it to 2223. This is: without the information after the ",". Assume that there will be only two decimals after the ",".
I did:
str = str.Remove(str.Length - 3, 3);
Is there a more elegant solution? Maybe using another function? -I donĀ“t like putting explicit numbers-
You can actually just use the Remove overload that takes one parameter:
str = str.Remove(str.Length - 3);
However, if you're trying to avoid hard coding the length, you can use:
str = str.Remove(str.IndexOf(','));
Perhaps this:
str = str.Split(",").First();
This will return to you a string excluding everything after the comma
str = str.Substring(0, str.IndexOf(','));
Of course, this assumes your string actually has a comma with decimals. The above code will fail if it doesn't. You'd want to do more checks:
commaPos = str.IndexOf(',');
if(commaPos != -1)
str = str.Substring(0, commaPos)
I'm assuming you're working with a string to begin with. Ideally, if you're working with a number to begin with, like a float or double, you could just cast it to an int, then do myInt.ToString() like:
myInt = (int)double.Parse(myString)
This parses the double using the current culture (here in the US, we use . for decimal points). However, this again assumes that your input string is can be parsed.
String.Format("{0:0}", 123.4567); // "123"
If your initial value is a decimal into a string, you will need to convert
String.Format("{0:0}", double.Parse("3.5", CultureInfo.InvariantCulture)) //3.5
In this example, I choose Invariant culture but you could use the one you want.
I prefer using the Formatting function because you never know if the decimal may contain 2 or 3 leading number in the future.
Edit: You can also use Truncate to remove all after the , or .
Console.WriteLine(Decimal.Truncate(Convert.ToDecimal("3,5")));
Use:
public static class StringExtensions
{
/// <summary>
/// Cut End. "12".SubstringFromEnd(1) -> "1"
/// </summary>
public static string SubstringFromEnd(this string value, int startindex)
{
if (string.IsNullOrEmpty(value)) return value;
return value.Substring(0, value.Length - startindex);
}
}
I prefer an extension method here for two reasons:
I can chain it with Substring.
Example: f1.Substring(directorypathLength).SubstringFromEnd(1)
Speed.
You could use LastIndexOf and Substring combined to get all characters to the left of the last index of the comma within the sting.
string var = var.Substring(0, var.LastIndexOf(','));
You can use TrimEnd. It's efficient as well and looks clean.
"Name,".TrimEnd(',');
Try the following. It worked for me:
str = str.Split(',').Last();
Since C# 8.0 it has been possible to do this with a range operator.
string textValue = "2223,00";
textValue = textValue[0..^3];
Console.WriteLine(textValue);
This would output the string 2223.
The 0 says that it should start from the zeroth position in the string
The .. says that it should take the range between the operands on either side
The ^ says that it should take the operand relative to the end of the sequence
The 3 says that it should end from the third position in the string
Use lastIndexOf. Like:
string var = var.lastIndexOf(',');
Related
I have as input the string format CST-000000 and an integer with value 1
Upon using
string result = string.Format("CST-000000", 1);
the expected result should be CST-000001 instead of CST-000000
How could i create this string format dynamically?
For example
- CST-000 should produce CST-001
- HELLO000 should produce HELLO001
- CUSTOMER0000 should produce CUSTOMER0001
Assuming that:
You receive your format string from somewhere and you can't control what it looks like
Your format string ends with 1 or more zeros
If the format string is e.g. CST-00000 and your value is 123, you want the result to be CST-00123
You can do something like this:
Inspect your format string, and separate out the stuff at the beginning from the zeros at the end. It's easy to do this with Regex, e.g.:
string format = "CST-000000";
// "Zero or more of anything, followed by one or more zeros at the end of the string"
var match = Regex.Match(format, "(.*?)(0+)$");
if (!match.Success)
{
throw new ArgumentException("Format must end with one or more zeros");
}
string prefix = match.Groups[1].Value; // E.g. CST-
string zeros = match.Groups[2].Value; // E.g. 000000
Once you have these, note the "Zero placeholder" in this list of custom numeric format strings -- you can write e.g. 123.ToString("0000") and the output will be 0123. This lets you finish off with:
int value = 123;
string result = prefix + value.ToString(zeros);
See it on dotnetfiddle
String.Format requires a placeholder {n} with a zero-based argument number. You can also add it a format {n:format}.
string result = String.Format("CST-{0:000000}", 1);
You can also use String interpolation
string result = $"CST-{1:000000}"
The difference is that instead of a placeholder you specify the value directly (or as an expression). Instead of the Custom numeric format string, you can also use the Standard numeric format string d6: $"CST-{1:d6}"
If you want to change the format template dynamically, String.Format will work better, as you can specify the format and the value as separate arguments.
(Example assumes an enum FormatKind and C# >= 8.0)
int value = 1;
string format = formatKind switch {
FormatKind.CstSmall => "CST-{0:d3}",
FormatKind.CstLarge => "CST-{0:d6}",
FormatKind.Hello => "HELLO{0:d3}",
FormatEnum.Customer => "CUSTOMER{0:d4}"
};
string result = String.Format(format, value);
Also note that the value to be formatted must be of a numeric type. Strings cannot be formatted.
See also: Composite formatting
It seems .toString("CST-000"), .toString("HELLO000") and so on, does the trick.
ToString and String.Format can do much more than use predefined formats.
For example :
string result = string.Format("CST-{0:000000}", 1);
string result = 1.ToString("CST-000000");
Should both do what you want.
(Of course you could replace "1" by any variable, even a decimal one).
I want to display 0.12345 as "+12.3%". Format string "P1" or "p1" gives "12.3%". I have tried both "+P1" and "+p1" to no avail.
string sFoo = 0.12345.ToString("P1");
Update
I should have emphasized that I always want the proper sign, not "+". If the number is -0.12345, "P1" works exactly as I want: "-12.3%".
Not quite using P1, but same result:
0.12345.ToString("+#.#%;-#.#%");
If you prefer at least one leading digit (e.g. "+0.23%" instead of "+.23%"):
0.12345.ToString("+0.#%;-0.#%"));
Same for trailing digits (e.g. "+14.0%" instead of "+14%"):
0.12345.ToString("+0.0%;-0.0%"));
Reference: https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-numeric-format-strings#the--section-separator
var num = 0.12345;
var sign = num > 0 ? "+" : "";
var output = $"{sign}{num.ToString("P1")}";
I'm afraid there is no format string to display the positive sign. I've searched in NumberFormatInfo if some custom format could accept this, but with no avail.
You can however build some extension methods to fit your needs :
public static string ToSignedPercent(this double input)
{
return $"{(input >= 0 ? "+" : "")}{input.ToString("P1")}";
}
// ...
Console.WriteLine((0.12345).ToSignedPercent()); // +12.3%
Console.WriteLine((-0.6789).ToSignedPercent()); // -67.9%
Fiddle
Put the following in your main method. basically this approaches just sets the variable sFoo to have format of percentage with two decimals.
string sFoo = String.Format("Value: {0:P2}.", 0.12345); // formats as 12.35%
Console.WriteLine(sFoo);
Substring these string:-
1. ZZ111122
2. ZZZZ222111
3. ZZZZZZZ333
4. ZZZ111333
I have these kind of strings. This value is always starting with Z. And after Z its always either 1 or 2 or 3. But i dont know the number of Zs in the string. So how can i extract all Z from the string
I don't know if I understood right. If you have "ZZZZ222111" and want only "222111", do it:
string test = "ZZZZ222111";
test = test.Substring(test.LastIndexOf("Z") + 1);
If you want only "ZZZZ", do it:
string test = "ZZZZ222111";
test = test.Substring(0, test.LastIndexOf("Z"));
Both ways are very simple. No need of loops or regular expressions.
Sounds like you're going to want to use regular expressions for this.
Use String.Trim function:
ZeroZValue = stringValue.Trim('Z');
String test = "ZZ111122";
String zOnly = test.Substring(0, test.IndexOfAny("123".ToCharArray()));
Take advantage of IndexOfAny(). I am assuming you want only Z's left over ("extract all Z from the string").
This is not difficult. I recommend processing the text line by line.
You can loop the string character by character. You can use regular expressions. Or you could use my sscanf() replacement class for C#.
int start = someString.IndexOf("Z");
int end = someString.LastIndexOf("Z");
someString.Substring(start , end - start);
I have -$2.00 as the string. I am trying to change it to decimal by removing - and $ using substring, but I am doing it wrong. Can someone help me?
Thanks.
string m = "-$2.00";
decimal d = Math.Abs(Decimal.Parse(m, NumberStyles.Currency));
Substring will return a new string. I suspect your issue is likely from trying to mutate the string in place, which does not work.
You can do:
string result = original.Substring(2);
decimal value = decimal.Parse(result);
Depending on how the input string is generated, you may want to use decimal.TryParse instead, or some other routine with better error handling.
Don't.
Instead, you should make .Net do the dirty work for you:
Decimal value = Decimal.Parse("-$2.00", NumberStyles.Currency);
If, for some reason, you don't want a negative number, call Math.Abs.
All string operations return a new string, because string is immutable
I wouldn't use substring if you can avoid it. It would be much simpler to do something like:
string result = original.Replace("$", "").Replace("-", "");
I have a string consist of integer numbers followed by "|" followed by some binary data.
Example.
321654|<some binary data here>
How do i get the numbers in front of the string in the lowest resource usage possible?
i did get the index of the symbol,
string s = "321654654|llasdkjjkwerklsdmv"
int d = s.IndexOf("|");
string n = s.Substring(d + 1).Trim();//did try other trim but unsuccessful
What to do next? Tried copyto but copyto only support char[].
Assuming you only want the numbers before the pipe, you can do:
string n = s.Substring(0, d);
(Make it d + 1 if you want the pipe character to also be included.)
I might be wrong, but I think you are under the impression that the parameter to string.Substring(int) represents "length." It does not; it represents the "start-index" of the desired substring, taken up to the end of the string.
s.Substring(0,d);
You can use String.Split() here is a reference http://msdn.microsoft.com/en-us/library/ms228388%28VS.80%29.aspx
string n = (s.Split("|"))[0] //this gets you the numbers
string o = (s.Split("|"))[1] //this gets you the letters