Why doesn't this string format as currency? - c#

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

Related

How to change the 3 in {0:f3} to an int from user input

Solved, thanks for the help!
So I got an assignment for school, and no matter how much I search the net or read my books I can't figure out the answer to the question.
I have done programming for about 4 hours, so thats why the question is phrased wierdly, I think.
Console.WriteLine("Enter a number with any number of decimals.");
string input;
input = Console.ReadLine();
decimal myNumber = decimal.Parse(input);
Console.WriteLine("Please specify how many decimals you want to be shown.");
string input2;
input22 = Console.ReadLine();
int myDecimal = int.Parse(input2);
Console.WriteLine(("Your number with the choosen number of decimals: {0:f3}"), myNumber);
So, when I run it and enter 2,1234567 as my number and 5 as my number of decimals, it prints 2,123 instead of 2,12345.
I know it prints 3 decimals because of the 3 after the f, but I can't figure out how to change the 3 into the ammount chosen by the user.
I have tried {0:f(myDecimal)}, {myDecimal:f and {0:f(int = myDecimal)} , none of which I expected to work as I was just testing things out.
The answer is probably really simple, and I'm probably just overthinking things, but help would be very much appriciated!
You need a format-ception here:
// the {{ and }} escapes to { and }
var numberFormat = string.Format("{{0:f{0}}}", myDecimal).Dump();
Console.WriteLine("Your number with the choosen number of decimals: " + numberFormat, myNumber);
You can use ToString too
decimal myNumber = 224323.545656M;
int myDecimal = 4;
Console.WriteLine(String.Format("Your number with the choosen number of decimals: {0} " , myNumber.ToString("F" + myDecimal)));
You could just simply change your last Console.WriteLine() call to this:
Console.WriteLine("Your number with the choosen number of decimals: {0}",
myNumber.ToString("f" + input2));
The part that changes is: myNumber.ToString("f" + input2). What this does is use string concatenation to build your format string from your variable input2.
I made a fiddle here.
Please keep in mind though, the format string you are using ("F") will round to that number of decimal places (i.e 1.236 would become 1.24 with format "F2")
You need to build the format string dynamically. At this point using a substituted string is harder than ToString:
var digits = 3;
var input = 2.123456789;
var format = $"F{digits}";
var output = "Some text {input.ToString(format)} some more text";

Fails when convert a number, reformat it to string in C#

I have a bug in my website when display salary.
If number insert < 1000$. It will show result like 0,x00.
Example:
user inserts to admin page salary: 800$. It will show like 0,800$.
If salary > 1000$, it shows correct.
My function to GetSalary() like:
public string GetSalary(object SalaryFrom, object SalaryTo)
{
return "$" + Protector.Int(SalaryFrom).ToString("0,000") + " - " + Protector.Int(SalaryTo).ToString("0,000");
}
Use ToString() by this way:
.ToString("#,000")
You can use the following format string to display a number with a maximum of 2 decimal places:
String.Format("{0:0.##}", 123.4567); // "123.46"
See Using String Format to show decimal upto 2 places or simple integer
0 in a format string means "absolutely show this digit". It sounds like you want something like this instead:
ToString("#,##0")
# means "a digit that might not be present".
Of course, this will still only show the thousands separator for thousands, and not millions. Another option might be using one of the pre-defined number formats - for example ToString("c") which will use the current culture's currency format (e.g. £1,234.00 for United Kingdom).
Try this code:
public string GetSalary(object SalaryFrom, object SalaryTo)
{
return "$" + #String.Format("{0:N}", SalaryFrom.ToString()) + " - " + #String.Format("{0:N}", SalaryTo.ToString());
}

Insert dynamic number format into interpolated string

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)}");

Format function to display custom character(s) if number is zero

I'm using the Format function ( http://msdn.microsoft.com/en-us/library/59bz1f0h%28v=vs.90%29.aspx ) to format my output. Currently I use this format string:
TestStr1 = Format(5459.4, "##,##0.00")
TestStr2 = Format(0.4, "##,##0.00")
TestStr3 = Format(0.0, "##,##0.00")
The above code will return "5,459.40", "0.4" and "0.00" respectively. Now, if the value is equal to zero, I want to display "-" instead. How can I achieve that output without using if-else statement, just Format function?
Edit:
Aside from Pranay's article here I found an article from Microsoft, it's on the bottom part. http://msdn.microsoft.com/en-us/library/0c899ak8.aspx
Full Article : Format Number To Display
use
";" Section Separator
This allow to display number according to number sign. As you can see in below code the fmt variable which is format I am going to apply on my number here first format before ; is for positive number , second format is for negative number and last format is for the zero value. Basically its "Positive;negative;zero" format. You can see the what it does in output of this code.
Example :
double posValue = 1234;
double negValue = -1234;
double zeroValue = 0;
string fmt = "+##;-##;**Zero**";
Console.WriteLine("value is positive : " + posValue.ToString(fmt));
Console.WriteLine();
Console.WriteLine("value is negative : " +negValue.ToString(fmt));
Console.WriteLine();
Console.WriteLine("value is Zero : " + zeroValue.ToString(fmt));
Console.WriteLine();
Note:
in above example you just repalce Zero with "-" or char you want.
Although code is in c#.net but same you can achieve it in vb.net after all its ToString function formate change.

Format decimal for percentage values?

What I want is something like this:
String.Format("Value: {0:%%}.", 0.8526)
Where %% is that format provider or whatever I am looking for.
Should result: Value: %85.26..
I basically need it for wpf binding, but first let's solve the general formatting issue:
<TextBlock Text="{Binding Percent, StringFormat=%%}" />
Use the P format string. This will vary by culture:
String.Format("Value: {0:P2}.", 0.8526) // formats as 85.26 % (varies by culture)
If you have a good reason to set aside culture-dependent formatting and get explicit control over whether or not there's a space between the value and the "%", and whether the "%" is leading or trailing, you can use NumberFormatInfo's PercentPositivePattern and PercentNegativePattern properties.
For example, to get a decimal value with a trailing "%" and no space between the value and the "%":
myValue.ToString("P2", new NumberFormatInfo { PercentPositivePattern = 1, PercentNegativePattern = 1 });
More complete example:
using System.Globalization;
...
decimal myValue = -0.123m;
NumberFormatInfo percentageFormat = new NumberFormatInfo { PercentPositivePattern = 1, PercentNegativePattern = 1 };
string formattedValue = myValue.ToString("P2", percentageFormat); // "-12.30%" (in en-us)
Set your culture and "P" string format.
CultureInfo ci = new CultureInfo("en-us");
double floating = 72.948615;
Console.WriteLine("P02: {0}", (floating/100).ToString("P02", ci));
Console.WriteLine("P01: {0}", (floating/100).ToString("P01", ci));
Console.WriteLine("P: {0}", (floating/100).ToString("P", ci));
Console.WriteLine("P0: {0}", (floating/100).ToString("P0", ci));
Console.WriteLine("P1: {0}", (floating/100).ToString("P1", ci));
Console.WriteLine("P3: {0}", (floating/100).ToString("P3", ci));
Output:
"P02: 72.95%"
"P01: 72.9%"
"P: 72.95%"
"P0: 72%"
"P1: 72.9%"
"P3: 72.949%"
If you want to use a format that allows you to keep the number like your entry this format works for me:
"# \\%"
This code may help you:
double d = double.Parse(input_value);
string output= d.ToString("F2", CultureInfo.InvariantCulture) + "%";
There's a simple and culture-independent approach: just use the "%" custom specifier and manually control the sign position.
https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-numeric-format-strings#SpecifierPct
A percent sign (%) in a format string causes a number to be multiplied by 100 before it is formatted. The localized percent symbol is inserted in the number at the location where the % appears in the format string.
string.Format("{0:0.0%}", 0.6493072393590115)
// outputs 64.9%
string.Format("{0:%000}", 0.6493072393590115)
// outputs %065
I have found the above answer to be the best solution, but I don't like the leading space before the percent sign. I have seen somewhat complicated solutions, but I just use this Replace addition to the answer above instead of using other rounding solutions.
String.Format("Value: {0:P2}.", 0.8526).Replace(" %","%") // formats as 85.26% (varies by culture)

Categories