Insert dynamic number format into interpolated string - c#

C# 6.0 brings this nifty new formatting operation indicated by a $
Instead of doing this
String lastName = "Doena";
String firstName = "DJ";
Console.WriteLine(String.Format("{1} {0}", lastName, firstName));
you can do this
Console.WriteLine($"{firstName} {lastName}");
But what about number formats. What if I have this:
Decimal price = 9999.95m;
Decimal freebie = 0;
const String format = "#,##0.##";
Console.WriteLine(String.Format("{0:" + format + "}\t{1:" + format + "}", price, freebie));
I tried this:
Console.WriteLine($"{price:"{format}"}\t{freebie:"{format}"}");
and this:
Console.WriteLine($"{price:{format}}\t{freebie:{format}}");
and this:
Console.WriteLine($"{price:format}\t{freebie:format}");
But they either not even compile or do not bring the hoped result.
Any ideas?
Edit Howwie's answer seems to be the reasonable way to go here:
Console.WriteLine($"{price.ToString(format)}\t{freebie.ToString(format)}");

Howwie's answer seems to be the reasonable way to go here:
Console.WriteLine($"{price.ToString(format)}\t{freebie.ToString(format)}");

Related

Is there a more optimal way to concatenate this string

I was wondering if there's a more simple way to concatenate this string instead of declaring a temporary variable
string tempValue = "000000000000000" + moneyValue;
moneyValue= tempValue.Substring((tempValue).Length - 15, 15);
I'm looking to a shorter way of achieving same result , is there any?
It looks like you are looking for a more succinct way to left-pad a string with zeroes.
.NET has a built-in method for that:
moneyValue = moneyValue.PadLeft(15, '0');
PadLeft works when you start with a string. If you want to combine zero padding with formatting of a number, you can use D15 format for integers
int moneyValue = 123456;
string moneyString = $"{moneyValue:D15}";
or a custom format for other numeric types
decimal moneyValue = 1234.56;
string moneyString = $"{moneyValue:000000000000000}";

How remove decimal part from string?

how to trim decimal part in given string of a decimal value in C#. im getting 20472.060 desired o/p - 20472
decimal totalamountWithTaxes = pri + result1 + result2 ;
string totalAmountPlusTaxes = totalamountWithTaxes.ToString();
You can simply do it like this:
int number = (int) totalAmountPlusTaxes;
or
string totalAmountPlusTaxes = String.Format("{0:C0}",totalamountWithTaxes);
Int32 Amount = Convert.ToInt32(totalamountWithTaxes.ToString().Substring(0,totalamountWithTaxes.ToString().IndexOf(".")));
Yes the above example is right and also I recommend you to visit:
String.Format Method-MSDN

How can I convert formatted string to int (if I know format) in C#?

I have formatted string, for example 123 456 000$ and I know format of this string {0:### ### ##0}$. I'd like to get int value = 123456000; from this string in C# with using known format.
How I can do that?
mytext = System.Text.RegularExpressions.Regex.Replace(mytext.Name, "[^.0-9]", "");
or something approximately like that get's rid of the pesky non-numbers
and then delete the first few characters 1,2,3... and last few length, length -1, length -3...
unless I'm missing something?
Oh yeah, and Convert.Toint32(mytext)
int.Parse("123 456 000$", NumberStyles.AllowCurrencySymbol |
NumberStyles.Number);
http://msdn.microsoft.com/en-us/library/c09yxbyt.aspx
I think you will have to construct a similar NumberFormatInfo to parse the string value.$ for the currency symbol used in the text and in your case the thousand group seperator is space instead of , so a custom number format info should help you parse it.
string val = "123 456 000$";
NumberFormatInfo numinf = new NumberFormatInfo();
numinf.CurrencySymbol = "$";
numinf.CurrencyGroupSeparator = " ";
numinf.NumberGroupSeparator = " "; // you have space instead of comma as the seperator
int requiredval = int.Parse(val,NumberStyles.AllowCurrencySymbol | NumberStyles.AllowThousands, numinf);
This should help you get the value
I would make it easy way:
String formattedString = "12345500$";
formattedString.Remove(formattedString.Length - 1);
int value = int.Parse(formattedString);

Format string for decimal output

I just started programming C# today, and I'm trying to get a handle on the format strings.
I would like to output a string of this format:
{decimal number using a maximum of 10 columns} +
" " +
{decimal number taking a maximum of 10 columns}
I've tried
String outputFormat = "{0,-10:0.#####} {1,-10:0.#####}";
String output = String.Format(outputFormat, x, y);
But if x is 34059834.340598, I don't get the output I want.
The first number takes more than 10 columns.
Is there a format string to force numbers to 10 columns? (Maybe show E notation if the n.m would be greater than 10 columns).
I think you are looking for the G specifier for you number formating.
Something like this (untested) should work:
string tenCols = myDecimal.ToString("G10");
Or to be more inline with what you had before, I think this should do it:
String outputFormat = "{0,-10:G10} {1,-10:G10}";
String output = String.Format(outputFormat, x, y);
double x = 34059834.340598
string displayX = x.ToString().Substring(0,10);
I'm pretty sure you won't be able to do what you want using format strings directly, but it's easy enough with string manipulation in code.

Why doesn't this string format as currency?

I have the following line:
//Send Email
clntMailBody = clntMailBody + "Order Total: " + String.Format("{0:C}", strOrderTotal + "\n");
Watch shows:
String.Format("{0:C}", strOrderTotal + "\n") "35\n" string
But it only outputs "35". I expected "$35.00" Why is this not working as intended?
Thanks
I'm guessing strOrderTotal is a string? I think {0:C} only works for decimal or int types.
I can't believe all of these answers and no one mentioned this, change your code to
clntMailBody = clntMailBody + "Order Total: " + String.Format("{0:C}", strOrderTotal) + "\n";
And see if that solves your problem, however a better way to do it would be
clntMailBody = String.Format("{0}Order Total: {1:C}\n", clntMailBody, strOrderTotal);
It is much easier to see what is going on and removes a lot of your string concatenation.
If you are willing to do some more re-writing a even better solution is: (I made some logic up to show my example)
StringBuilder clntMailBody = new StringBuilder();
clntMailBody.AppendLine("Some Fixed body Text")
foreach(string lineItem in Invoice)
{
clntMailBody.AppendLine(lineItem);
}
clntMailBody.AppendFormat("Order Total {0:C}", strOrderTotal).AppendLine();
return clntMailBody.ToString();
You haven't shown the declaration of strOrderTotal but by it's name I assuming it's already a string. As it's already a string the formatting won't work.
If you want the formatting to work you'll need to pass the order total in as a number - preferably a decimal.
Because it is a string.
Trying to format a string returns... the string.
You need a numeric value in order to get it formatted as currency.
You will see that the C format specifier is defined in the Standard Numeric Format String page on MSDN. Numeric, not "strings".
I presume that strOrderTotal is string ? It had to be decimal, or double etc
I'm going to assume that strOrderTotal is a string. You should use a numeric type, like double or Decimal.
It looks like (based on the variable name strOrderTotal) that your total is already a string. The "C" format specifier converts a number to currency format, not something that's already a string.
Therefore you need to either manually format your string as currency or apply the currency format when the order total is originally converted to a string (when it's stored in strOrderTotal).
If strOrderTotal is a string you can use this code to format it for currency
clntMailBody = clntMailBody + "Order Total: " + String.Format("{0:C}", decimal.Parse(strOrderTotal) + "\n");
To display a string in the currency format:
StringBuilder sb= new StringBuilder("Your total amount is ");
sb.AppendFormat("{0:C} ", 25 );
Console.WriteLine(sb);
Output:
Your total amount is $25.00

Categories