String to string format - c#

I have a string which contains numbers, and I want to show this string in this numeric format: #,##0
So i try to add to this string .ToString("#,##0") but the compiler says that
The best overloaded method match for
'string.ToString(System.IFormatProvider)' has some invalid arguments.
Any idea how to do that without converting this string first into int ?

When you just need to format a single number, like an integer or long. In this case, you don't need to use string.Format.You can just use the ToString virtual method. This reduces some overhead. But you can't format a string directly using ToString.

I don't think it is possible unless you want to process the string manually. If you try String.Format("{0:#,##0}", "1000000") the output is 1000000. And to me, this makes sense. While you can say "this string contains numbers all the time", that is not a safe assumption to the language to make normally.
Your best bet is to do something like:
String.Format("{0:#,##0}", int.Parse(input));
if you're sure it will always will be a castable integer.

please first convert string input to the integer and then try formatting the string. Please see the example below:
string test = "12345";
Console.WriteLine("{0}", int.Parse(test).ToString("#,##0"));

Related

Prevent C# from using 'E+x' with large numbers [duplicate]

How to convert double to string without the power to 10 representation (E-05)
double value = 0.000099999999833333343;
string text = value.ToString();
Console.WriteLine(text); // 9,99999998333333E-05
I'd like the string text to be 0.000099999999833333343 (or nearly that, I'm not doing rocket science:)
I've tried the following variants
Console.WriteLine(value.ToString()); // 9,99999998333333E-05
Console.WriteLine(value.ToString("R20")); // 9,9999999833333343E-05
Console.WriteLine(value.ToString("N20")); // 0,00009999999983333330
Console.WriteLine(String.Format("{0:F20}", value)); // 0,00009999999983333330
Doing tostring N20 or format F20 seems closest to what I want, but I do end up with a lot of trailing zeros, is there a clever way to avoid this? I'd like to get as close to the double representation as possible 0.000099999999833333343
Use String.Format() with the format specifier. I think you want {0:F20} or so.
string formatted = String.Format("{0:F20}", value);
How about
Convert.ToDecimal(doubleValue).ToString()
You don't need string.Format(). Just put the right format string in the existing .ToString() method. Something like "N" should do.
Use string.Format with an appropriate format specifier.
This blog post has a lot of examples: http://blogs.msdn.com/kathykam/archive/2006/03/29/564426.aspx

Which of one from string interpolation and string.format is better in performance?

Consider this code:
var url = "www.example.com";
String.Format:
var targetUrl = string.Format("URL: {0}", url);
String Interpolation:
var targetUrl=$"URL: {url}";
Which of one from string interpolation and string.Format is better in performance?
Also what are the best fit scenarios for use of them?
According to C# docs string interpolation so maybe there is no difference at all?
... it's typically transformed into a String.Format method call
Which of one from string interpolation and string.format is better in performance?
Neither of them is better since they are equal on run-time. String interpolation is rewritten by the compiler to string.Format, so both statements are exactly the same on run-time.
Also what are the best fit scenarios for use of them?
Use string interpolation if you have variables in scope which you want to use in your string formatting. String interpolation is safer since it has compile time checks on the validness of your string. Use string.Format if you load the text from an external source, like a resource file or database.
Under most conditions they're the same, but not if you're using them in a logging statement that accepts a format string. (ex: log.Debug("URL: {0}", url))
If you use the {0} format, the argument won't get translated into a string until after the logging framework has decided whether or not to emit this message, whereas the {myVar} format is translated to a string before the function is entered.
Hence, in a log.Debug() call where you're only outputting Info and above, the {myVar} format always pays the binary to text tax, whereas the {0} format only pays the tax when you actually want it.
In the case of passing a string it doesn't matter, but for binary data and floating point data it can make quite a difference.

Surprising int.ToString output

I have been working on a project, and found an interesting problem:
2.ToString("TE"+"000"); // output = TE000
2.ToString("TR"+"000"); // output = TR002
I also have tried with several strings other than "TE" but all have the same correct output.
Out of curiosity, I am wondering how come this could have happened?
Simply based on Microsoft's documentation, Custom Numeric Format Strings, your strings "TE000" and "TR000" are both custom format strings, but clearly they are parsed differently.
2.ToString("TE000") is just a bug in the formatter; it's going down a buggy path because of the unescaped "E". So it's unexpectedly assuming the whole thing is a literal.
2.ToString("TR000") is being interpreted as an implied "TR" literal plus 3 zero-filled digits for an integer value; therefore, you get "TR002".
If you truly want TE and TR verbatim, the expressions 2.ToString("\"TE\"000") and 2.ToString("\"TR\"000") will accomplish that for you by specifying TE and TR as explicit literals, instead of letting the formatter guess if they are valid format specifiers (and getting it wrong).
The ToString needs to PARSE the format string and understand what to do with it.
Let's take a look to the following examples:
2.ToString("TE000"); //output TE000
2.ToString("E000"); //output 2E+000
2.ToString("0TE000); //output 2TE000
2.ToString("T"); //throws exception
2.ToString("TT"); //output TT
This shows that if the ToString parser can understand at least part of the format, it will assume that the rest is just extra characters to print with it. If the format is invalid for the given number (like when you use a DateTime string format on a number), it will throw an exception. If it can not make sense of the format, it will return the format string itself as the result.
You cannot use a numeric format to achieve a custom format, instead use something like this:
int i = 2;
String.Format("TE{0:X3}", i);
See Custom Numeric Format Strings. The E means the exponent part of the scientific notation of the number. Since 2 is 2E000 in exponential notation, that might explain it.

Format a long string into a short string C#

I have some strings such as:
1.5555555555555
2.3421354325435354545
4.509019292
I want to format them into a string such as:
1.5555
2.3421
4.5090
I tried to use the C# String.Format but I can not get it to correctly work.
Can someone please give me the correct c# statement to accomplish this?
Thanks.
It's unclear if you'll always be dealing with numeric values. If you want to avoid parsing the strings as numbers, you might try something like this:
public static string TrimTo(string str, int maxLength)
{
if (str.Length <= maxLength)
{
return str;
}
return str.Substring(0, maxLength);
}
This will trim the provided string to six characters, if it's longer than six. This seems to be what you want, but (as Kees points out), will do something unexpected with a string like "1234567.890".
The conditional clause is necessary here because String.Substring will complain if the second index is outside of the string (if the string is shorter than maxLength, in other words).
(If you've played around with C# 3.0 extension methods at all, you might recognize this, slightly modified from the above, as an excellent opportunity for one: string trimmed = s.TrimTo(10);)
string.Format("{0:N4}",decimalValue);
Standard Numeric Format Strings
Custom Numeric Format Strings
If you convert the Strings to doubles you can use String.Format to specify how many decimal places you want to include when you reformat it as a String.
String.Format("{0:0.0000}", double.Parse("1.55555555555555"))

how to get a String with String.Format to execute?

I have a little chunk of code (see below) that is returning the string:
string.Format("{0}----{1}",3,"test 2");
so how do I get this to actually "Execute"? To run and do the format/replacement of {0} and {1}?
My Code snippet:
StringBuilder sb = new StringBuilder();
sb.Append("{0}----{1}\",");
sb.AppendFormat(ReturnParamValue(siDTO, "siDTO.SuggestionItemID,siDTO.Title"));
string sbStr = "=string.Format(\""+sb.ToString()+");";
yes, ReturnParamValue gives the actually value of the DTO.
Anyways, I've taken a look at the following (but it doesn't say how to execute it:
How to get String.Format not to parse {0}
Maybe, I just should put my code snippet in a method. But, what then?
Why are you including String.Format in the string itself?
If you're looking for a generic "let me evaluate this arbitrary expression I've built up in a string" then there isn't a simple answer.
If, instead, you're looking at how to provide the parameters to the string from a function call, then you've got yourself all twisted up and working too hard.
Try something like this, based on your original code:
string result
= string.Format(
"{0}----{1}",
ReturnParamValue(siDTO, "siDTO.SuggestionItemID,siDTO.Title"));
Though, this won't entirely work since your original code seems to be only providing a single value, and you have two values in your format string - the {0} will be replaced with the value from your function, and {1} left unchanged.
What output are you expecting?
Does your ReturnParamValue() function try to return both the label and the value in a single string? If it does, and if they're comma separated, then you could try this:
var value = ReturnParamValue(siDTO, "siDTO.SuggestionItemID,siDTO.Title"));
var pieces = string.Split(',');
string result
= string.Format( "{0}----{1}", pieces[0], pieces[1]);
Though this is seriously working too hard if ReturnParamValue() is a method you control.
Update Fri 6 August
Check out the declaration for string.Format() as shown on MSDN:
public static string Format(
string format,
params Object[] args
)
Unlike the special casing you might have seen in C for printf(), there's nothing special or unusual about the way string.Format() handles multiple parameters. The key is the params keyword, which asks the compiler to provide a little "syntactic sugar" where it combines the parameters into an array for you.
Key here is that the wrapping doesn't happen if you're already passing a single object[] - so if you wanted to, you could do something like this:
object[] parameters
= ReturnParamValues(siDTO, "siDTO.SuggestionItemID,siDTO.Title");
string result
= string.Format("{0}----{1}----{2}", parameters);
Though, if I saw something like this in any codebase I maintained, I'd be treating it as a code-smell and looking for a better way to solve the problem.
Just because it's possible doesn't mean it's advisable. YMMV, of course.
I don't think you can execute it. Java is not really a interpreted language.
You may make use of scripting languages (which can even embed in your Java app as I know, start from JDK6) for such purpose, like Groovy
You could use RegEx to parse the three parameters out of the string, and then pass them to a real, actual string.Format method :-)
It looks like what you want is something like this:
string sbStr = string.Format("{0}----{1}", siDTO.SuggestionItemID, siDTO.Title);
Maybe i didn't understand your question completely, but it sounds like you need to format a format-string. If that's true you could maybe try something like this:
int width = 5;
string format = String.Format("{{0,{0}}}----{{1,{0}}}", width);
string result = String.Format(format, "ab", "cd");
So the trick is simply to escape the { or } by using a double {{ or }}.

Categories

Resources