C# 6 how to format double using interpolated string? - c#

I have used interpolated strings for messages containing string variables like $"{EmployeeName}, {Department}". Now I want to use an interpolated string for showing a formatted double.
Example
var aNumberAsString = aDoubleValue.ToString("0.####");
How can I write it as an interpolated string? Something like $"{aDoubleValue} ...."

You can specify a format string after an expression with a colon (:):
var aNumberAsString = $"{aDoubleValue:0.####}";

A colon after the variable specifies a format,
Console.Write($"{aDoubleValue:0.####}");

Or like this:
Console.Write($"{aDoubleValue:f4}");

Related

How can i create a dynamic string format in C#

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).

Using variable to define string.Format numeric format style

I'd like to format a number using a run-time supplied format string.
Isn't something like this possible?
string.Format("{0:{1}}",0,"c")
The "c" may change to be any other type of format string. I've tried various combinations but am failing to find the correct one.
This should work:
var s0 = string.Format("{{0:{0}}}", "c");
var s1 = string.Format(s0, 0);
The double { and } is to escape curly braces.

c# remove trailing 0 for INR currency conversion?

I use following code to convert input to comma separated string in INR:
decimal input = 1111111111.59m;
string result = input.ToString("C", new CultureInfo("EN-in"));
I want to remove the trailing 0s now, how do i do this?
for example:
decimal input = 1111111111.00m;
Output should be 1111111111
string result = input.ToString("c0", new CultureInfo("EN-in"));
Update:
So you want output "123.45" for input 123.45 and output "123" for input 123.00.
You can't achieve these 2 different formats without conditional operator, String.Format() will produce only one output format for you.
The code is simple though:
string format = Decimal.Round(input) == input ? "c0" : "c";
string output = input.ToString(format);
string output = input.ToString("0");
Following code should work :
string results = input.ToString("0.##");
The simplest thing to convert is convert into int.
int d = convert.toInt32(1111.00);
or use any math function as suggested.
How to remove decimal part from a number in C#
How do I format a C# decimal to remove extra following 0's?
Edit
As I understand just try
Console.WriteLine(d.ToString("0.#####"));
Seet this url :- Best way to display decimal without trailing zeroes

Fixed string Regular Expression C#

Hi all I want to know something regarding to fixed-string in regular expression.
How to represent a fixed-string, regardless of special characters or alphanumeric in C#?
For eg; have a look at the following string:
infinity.world.uk/Members/namelist.aspx?ID=-1&fid=X
The entire string before X will be fixed-string (ie; the whole sentence will appear the same) BUT only X will be the decimal variable.
What I want is that I want to append decimal number X to the fixed string. How to express that in terms of C# regular expression.
Appreciate your help
string fulltext = "inifinity.world.uk/Members/namelist.aspx?ID=-1&fid=" + 10;
if you need to modify existing url, dont use regex, string.Format or string.Replace you get problem with encoding of arguments
Use Uri and HttpUtility instead:
var url = new Uri("http://infinity.world.uk/Members/namelist.aspx?ID=-1&fid=X");
var query = HttpUtility.ParseQueryString(url.Query);
query["fid"] = 10.ToString();
var newUrl = url.GetLeftPart(UriPartial.Path) + "?" + query;
result: http://infinity.world.uk/Members/namelist.aspx?ID=-1&fid=10
for example, using query["fid"] = "%".ToString(); you correctly generate http://infinity.world.uk/Members/namelist.aspx?ID=-1&fid=%25
demo: https://dotnetfiddle.net/zZ9Y1h
String.Format is one way of replacing token values in a string, if that's what you want. In the example below, the {0} is a token, and String.Format takes the fixedString and replaces the token with the value of myDecimal.
string fixedString = "infinity.world.uk/Members/namelist.aspx?ID=-1&fid={0}";
decimal myDecimal = 1.5d;
string myResultString = string.Format(fixedString, myDecimal.ToString());

adding quotes around date and time, c#

I am currently using the following line:
w.Write(DateTime.Now.ToString("MM/dd/yyyy,HH:mm:ss"));
and it gives and output like:
05/23/2011,14:24:54
What I need is quotations around the date and time, the output should look like this:
"05/23/2011","14:24:54"
any thoughts on how to "break up" datetime, and get quotes around each piece?
Try String.Format:
w.Write(String.Format("\"{0:MM/dd/yyyy}\",\"{0:HH:mm:ss}\"", DateTime.Now));
DateTime.Now.ToString("\\\"MM/dd/yyyy\\\",\\\"HH:mm:ss\\\"")
This will do the trick, too.
string format = #"{0:\""MM/dd/yyyy\"",\""HH:mm:ss\""}" ;
string s = string.Format(format,DateTime.Now) ;
as will this:
string format = #"{0:'\""'MM/dd/yyyy'\""','\""'HH:mm:ss'\""'}" ;
string s = string.Format(format,DateTime.Now) ;
and this
string format = #"{0:""\""""MM/dd/yyyy""\"""",""\""""HH:mm:ss""\""""}" ;
string s = string.Format(format,DateTime.Now) ;
The introduction of a literal double quote (") or apostrophe (') in a DateTime or Numeric format strings introduces literal text. The embedded literal quote/apostrophe must be balanced — they act as an embedded quoted string literal in the format string. To get a double quote or apostrophe it needs to be preceded with a backslash.
John Sheehan's formatting cheatsheets makes note of this...feature, but insofar as I can tell, the CLR documentation is (and always has been) incorrect WRT this: the docs on custom date/time and numeric format strings just says that "[any other character] is copied to the result string unchanged.".
string part1 = DateTime.Now.ToString("MM/dd/yyyy");
string part2 = DateTime.Now.ToString("HH:mm:ss");
Console.WriteLine("\""+part1+"\",\""+part2+"\"");
Works just fine. May not be the best way though
I'm not sure about the type of w but if it supports the standard set of Write overloads the following should work.
w.Write(#"""{0}""", DateTime.Now.ToString(#"MM/dd/yyyy"",""HH:mm:ss")));
If not then you can do the following
var msg = String.Format(#"""{0}""", DateTime.Now.ToString(#"MM/dd/yyyy"",""HH:mm:ss"))));
w.Write(msg);
The following version, though obvious, will not work:
w.Write(DateTime.Now.ToString("\"MM/dd/yyyy\",\"HH:mm:ss\""));
This will output:
MM/dd/yyyy,HH:mm:ss
So don't do that.

Categories