Variable decimal formating in string interpolation - c#

I have looked around for this, but I'm not sure it's possible with string interpolation (I'm using VS2015).
string sequenceNumber = $"{fieldValuePrefix.ToUpper()}{separator}{similarPrefixes + 1:D4}";
Is there any way to make D4 a variable ? Some say yes, some no. Apparently, VS2015 C#6.0 is able to do it.
This works, it will return a string like WMT-0021, depending on fieldValuePrefix (WMT), separator (-) and the value of similarPrefixes (20). But I'd like the "D4" part to be a method argument instead of hardcoded in there.
Any ideas ?

You can, but you have to use explicit ToString call like this:
string format = "D4";
string sequenceNumber =
$"{fieldValuePrefix.ToUpper()}{separator}{(similarPrefixes + 1).ToString(format)}";

Related

Is there a way to Ignore escape characters but still use string interpolation? C#

So, the string I need to implement is this, I am using .Net 4.5.2 in c# in visual studio 2019, I want the espected output to be exactly as below albeit with FIRSTNAME being replaced by a variable.
beneficiaryFirstName: \\\"FIRSTNAME\\\"
This is being used with a lot of similarly structured strings to join them together to form a large graphQL query. The problem I have is that VStudio keeps throwing up errors.
Edit : I would like to make clear, I need the \'s in the string result, and I need FIRSTNAME to be treated as a variable.
I have attempted to use this.
$#"beneficiaryFirstName: \\\"{{FIRSTNAME}}\\\""
But get told that it there's unexpected characters "" and "".
What is the best way around this?
You just need the right escaping
var FIRSTNAME = "Bob";
var pad = #"\\\";
var test1 = $"beneficiaryFirstName: \\\\\\\"{FIRSTNAME}\\\\\\\"";
var test2 = #$"beneficiaryFirstName: \\\""{FIRSTNAME}\\\""";
var test3 = $"beneficiaryFirstName: {pad}\"{FIRSTNAME}{pad}\"";
Console.WriteLine(test1);
Console.WriteLine(test2);
Console.WriteLine(test3);
Output
beneficiaryFirstName: \\\"Bob\\\"
beneficiaryFirstName: \\\"Bob\\\"
beneficiaryFirstName: \\\"Bob\\\"
Disclaimer, I am not sure if the quotes are correct in your example, they seem like they are in weird places, though that could be just how it is
you can do like this.
string FIRSTNAME = "YourName";
string temp = $"beneficiaryFirstName: {FIRSTNAME}";
Console.WriteLine(temp);
It will print
beneficiaryFirstName: YourName
You can try this string temp = $"beneficiaryFirstName: \\\\{FIRSTNAME}\\\\"; if you want outout
beneficiaryFirstName: \\YourName\\
As mentioned by the OP, you can use this to get the required output.
string temp = #$"beneficiaryFirstName: \\\{FIRSTNAME}\\\";

String concatenation using String interpolation

I've something like below.
var amount = "$1,000.99";
var formattedamount = string.Format("{0}{1}{0}", "\"", amount);
How can I achieve same using String interpolation?
I tried like below
var formattedamount1 = $"\"{amount}\"";
Is there any better way of doing this using string interpolation?
Update
Is there any better way of doing this using string interpolation
No, this is just string interpolation, you cant make the following any shorter and more readable really
var formattedamount1 = $"\"{amount}\"";
Original answer
$ - string interpolation (C# Reference)
To include a brace, "{" or "}", in the text produced by an
interpolated string, use two braces, "{{" or "}}". For more
information, see Escaping Braces.
Quotes are just escaped as normal
Example
string name = "Horace";
int age = 34;
Console.WriteLine($"He asked, \"Is your name {name}?\", but didn't wait for a reply :-{{");
Console.WriteLine($"{name} is {age} year{(age == 1 ? "" : "s")} old.");
Output
He asked, "Is your name Horace?", but didn't wait for a reply :-{
Horace is 34 years old.
Same thing you can achieve by doing:
var formattedamount1 = $"\"{amount}\"";
OR
var formattedamount1 = $#"""{amount}""";
It's basically allowing you to write string.Format(), but instead of using one string with "placeholders"({0}, {1}, .. {N}), you are directly writing/using your variable inside string.
Please read more about String Interpolation (DotNetPerls), $ - string interpolation to fully understand whats going on.
Just to give one more option, if you want to make sure you use the same quote at both the start and the end, you could use a separate variable for that:
string quote = "\"";
string amount = "$1,000.99";
string formattedAmount = $"{quote}{amount}{quote}";
I'm not sure I'd bother with that personally, but it's another option to consider.

Format a string like you would a numeric value

I have a string that I would like to format the same way I would a numeric value.
Ex:
int num = 2;
string option = num.ToString("000");
Console.WriteLine(option);
//output
//002
But the only way I can think to format it is to parse it as an int, then apply the ToString("000") method to it.
string option = "2";
option = int.Parse(option).ToString("000");
Is there a better, more direct way to do this?
No, there is no built-in mechanism to "format" a string as if it were a number. Some options:
Use string functions (Pad, Length, Substring) to determine what characters should be added
Parse to a numeric type and use ToString with numeric formatting strings
Use a reqular expression to extract the digits and generate a new string
There's not one "right" answer. Each has risks and benefits in terms of safety (what if the string does not represent a valid integer?), readability, performance, etc.
Would this suit your requirement?
string x = "2";
string formattedX = x.PadLeft(3, '0');
Console.WriteLine(formattedX); //prints 002

Get characters behind the dot in of a double

I feel like this is a very noob question.. but I just can't get the right statement for it.
For display purposes, I want to split a double in two: the part before the dot and the first two digits after the dot. I need it as a string. Target language: C#.
E.g.: 2345.1234 becomes "2345" and "12"
I know how to get the part before the dot, that's simply:
Math.Floor(value).ToString()
...but what is the right way to get the part "behind the dot"?
There must be some nice way to do that in a simple way...
I can't think of anything else then:
Math.Round(100 * (value - Math.Floor(value))).ToString("00");
I'm sure there is a better way, but I just can't think of it. Anyone?
Regular expressions (regex) is probably you best bet, but using the mod operator may be another valuable solution...
stuffToTheRight = value % 1
Cheers.
//
//Use the Fixed point formatting option. You might have a bit more work to do
//if you need to handle cases where "dot" is not the decimal separator.
//
string s = value.ToString("F2", CultureInfo.InvariantCulture);
var values = s.Split(".");
string v1 = values[0];
string v2 = values[1];
See this link for more about formatting: http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx
Here is some untested code that tries to take current culture into account:
//
//Use the Fixed point formatting option.
//
string s = value.ToString("F2", CultureInfo.CurrentCulture);
var values = s.Split(CultureInfo.NumberFormat.NumberDecimalSeparator);
string v1 = values[0];
string v2 = values[1];
use regex ".[0-9][0-9]"
In one line it will be:
string[] vals = value.ToString("f2").Split(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator.ToCharArray());
vals[0] : before point.
vals[1] : after point.

Good way to translate numeric to string, with decimal point removed?

I have to deal with a numeric value (coming from a SQL Server 2005 numeric column) which I need to convert to a string, with the caveat that the decimal point has to be removed. The data itself is accessible in C# via a DataTable/DataRow.
For example, if the SQL Server column reads 12345.678, the string should be "12345678" when all is said and done. Would it be possible to point me toward a good approach for this? Maybe there's a .Net conversion method that does this, I'm not sure.
Thanks!
There are several possible approaches. You could convert it to a string using a specific culture so that you are sure that the period is used as decimal separator, then remove the period:
string s = num.ToString(CultureInfo.InvariantCulture).Replace(".", String.Empty);
You could use a more numeric approach to multiply the valye by 10 until there are no decimals:
while (num != Math.Floor(num)) num *= 10.0;
string s = ((int)num).ToString();
what about something like
var numberWithPoint = dbGetNumber();
string numberWithOutPoint = numberWithPoint.ToString().Replace(".", string.Empty);
it's quick and dirty, but it get the job done fairly simply.
you can do it in c# like:
var myNum = 12345.678;
var myString = myNum.ToString().Replace(".","");
in sql server, you can do it like:
SELECT REPLACE( cast(myCol as varchar), '.', '') as FormattedNumber
FROM ...
What about:
// using System.Globalization;
SqlCommand cm = new SqlCommand("SELECT 12345.678 as decimal");
// ...
SqlDataReader dr = cm.ExecuteReader();
if(dr.Read())
{
string value = dr.GetValue(0).ToString()
.Replace(NumberFormatInfo.CurrentInfo.NumberDecimalSeparator, "")
}
but usually when it comes from sql server, you should not convert it first to a string than to integer / double but convert it directly from object in row["column1"] to needed value, this will save you troubles handling cultures and improve performance a bit
A straightforward method is to use
string result = original.Replace(".", "")
There might be a faster method, but if this isn't in a tight inner loop, Replace should work fine.
EDIT: Fixed code example, plus:
To address culture concerns, one might use NumberFormatInfo.NumberDecimalSeparator to determine the currently defined decimal separator.
string result = Regex.Replace(original, "[^0-9]", "");

Categories

Resources