Fails when convert a number, reformat it to string in C# - 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());
}

Related

string format money , [duplicate]

I need to display a number with commas and a decimal point.
Eg:
Case 1 : Decimal number is 432324 (This does not have commas or decimal points).
Need to display it as: 432,324.00.
Not: 432,324
Case 2 : Decimal number is 2222222.22 (This does not have commas).
Need to display it as: 2,222,222.22
I tried ToString("#,##0.##"), but it is not formatting it correctly.
int number = 1234567890;
number.ToString("#,##0.00");
You will get the result 1,234,567,890.00.
Maybe you simply want the standard format string "N", as in
number.ToString("N")
It will use thousand separators, and a fixed number of fractional decimals. The symbol for thousands separators and the symbol for the decimal point depend on the format provider (typically CultureInfo) you use, as does the number of decimals (which will normally by 2, as you require).
If the format provider specifies a different number of decimals, and if you don't want to change the format provider, you can give the number of decimals after the N, as in .ToString("N2").
Edit: The sizes of the groups between the commas are governed by the
CultureInfo.CurrentCulture.NumberFormat.NumberGroupSizes
array, given that you don't specify a special format provider.
Try with
ToString("#,##0.00")
From MSDN
*The "0" custom format specifier serves as a zero-placeholder symbol. If the value that is being formatted has a digit in the position where the zero appears in the format string, that digit is copied to the result string; otherwise, a zero appears in the result string. The position of the leftmost zero before the decimal point and the rightmost zero after the decimal point determines the range of digits that are always present in the result string.
The "00" specifier causes the value to be rounded to the nearest digit preceding the decimal, where rounding away from zero is always used. For example, formatting 34.5 with "00" would result in the value 35.*
I had the same problem. I wanted to format numbers like the "General" format in spreadsheets, meaning show decimals if they're significant, but chop them off if not. In other words:
1234.56 => 1,234.56
1234 => 1,234
It needs to support a maximum number of places after the decimal, but don't put trailing zeros or dots if not required, and of course, it needs to be culture friendly. I never really figured out a clean way to do it using String.Format alone, but a combination of String.Format and Regex.Replace with some culture help from NumberFormatInfo.CurrentInfo did the job (LinqPad C# Program).
string FormatNumber<T>(T number, int maxDecimals = 4) {
return Regex.Replace(String.Format("{0:n" + maxDecimals + "}", number),
#"[" + System.Globalization.NumberFormatInfo.CurrentInfo.NumberDecimalSeparator + "]?0+$", "");
}
void Main(){
foreach (var test in new[] { 123, 1234, 1234.56, 123456.789, 1234.56789123 } )
Console.WriteLine(test + " = " + FormatNumber(test));
}
Produces:
123 = 123
1234 = 1,234
1234.56 = 1,234.56
123456.789 = 123,456.789
1234.56789123 = 1,234.5679
Try with
ToString("#,##0.###")
Produces:
1234.55678 => 1,234.556
1234 => 1,234
For Razor View:
$#string.Format("{0:#,0.00}",item.TotalAmount)
CultureInfo us = new CultureInfo("en-US");
TotalAmount.ToString("N", us)
Your question is not very clear but this should achieve what you are trying to do:
decimal numericValue = 3494309432324.00m;
string formatted = numericValue.ToString("#,##0.00");
Then formatted will contain: 3,494,309,432,324.00
All that is needed is "#,0.00", c# does the rest.
Num.ToString("#,0.00"")
The "#,0" formats the thousand separators
"0.00" forces two decimal points
If you are using string variables you can format the string directly using a : then specify the format (e.g. N0, P2, etc).
decimal Number = 2000.55512016465m;
$"{Number:N}" #Outputs 2,000.55512016465
You can also specify the number of decimal places to show by adding a number to the end like
$"{Number:N1}" #Outputs 2,000.5
$"{Number:N2}" #Outputs 2,000.55
$"{Number:N3}" #Outputs 2,000.555
$"{Number:N4}" #Outputs 2,000.5551
string Mynewcurrency = DisplayIndianCurrency("7743450.00");
private string DisplayIndianCurrency(string EXruppesformate)
{
string fare = EXruppesformate;
decimal parsed = decimal.Parse(fare, CultureInfo.InvariantCulture);
CultureInfo hindi = new CultureInfo("en-IN");
// string text = string.Format(hindi, "{0:c}", parsed);if you want <b>Rs 77,43,450.00</b>
string text = string.Format(hindi, "{0:N}", parsed); //if you want <b>77,43,450.00</b>
return ruppesformate = text;
}
For anyone looking at this now, and getting the "No overload for method 'ToString' takes 1 argument" when using:
TotalNumber.ToString("N")
My solution has been to use :
TotalNumber.Value.ToString("N")
I often get stuck on this when working directly inside an MVC View, the following wasn't working:
#Model.Sum(x => x.Number).ToString("N")
Whereas this works:
#Model.Sum(x => x.Number).Value.ToString("N")

Format decimal to money c# aspx from sql

Hi I have this code in my .cs file and the output is 100449.00 but I want it to format into money like 100,449.00. This is my code to show the value in the label.
billing.Text = "$" + ds.Tables[0].Rows[0]["Billing"].ToString();
billing.Text = "$" + ds.Tables[0].Rows[0]["Billing"].ToString("N");
Per this.
Edit: what's returned is an object which you need to cast to a decimal. Try:
((decimal)ds.Tables[0].Rows[0]["Billing"]).ToString("N");
billing.Text = ds.Tables[0].Rows[0]["Billing"].ToString("c");
Coming from a DataTable requires us to convert to a non-nullable type before we format as text.
We actually have a few different ways to do the formatting. Your post has a hardcoded dollar sign preceding the value, in which case we can use either the F2 or N2 format strings to give us a decimal point with 2 places to the right and append that to the dollar sign you have in there:
billing.Text = "$" + ((decimal)ds.Tables[0].Rows[0]["Billing"]).ToString("F2");
// 123456.7890 will display as $123456.78
billing.Text = "$" + ((decimal)ds.Tables[0].Rows[0]["Billing"]).ToString("N2");
// 123456.7890 will display as $123,456.78
Another option is to use the C format which will add in the cultural specific currency symbol and numeric format (decimal points, commas) for us
billing.Text = ((decimal)ds.Tables[0].Rows[0]["Billing"]).ToString("C");
// 123456.7890 will display as
// $123,456.78 en-US
// 123 456.78€ fr-FR
// you could also add a second overload to the ToString to specify

Remove decimal from currency

I am converting data for an export.
The file shows data in cents, not dollars.
So 1234.56 needs to be printed as 123456
Is there a way to do that with string.Format?
Or is the only solution to multiply by 100?
You can use string.Replace(".", string.empty). But that isn't exactly localized. You could add in cases where you check for "," as well for international currency. But that's what I would do.
[Edit]
Also just found this:
http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx
The "N" numeric specifier allows you to change the symbol used to separate whole number and decimal parts.
<code>
decimal num = 123.456m;
NumberFormatInfo ci = CultureInfo.CurrentCulture.NumberFormat;
ci.CurrencyDecimalSeparator = " "; // You can't use string.Empty here, as it throws an exception.
string str = num.ToString("N", ci).Replace(" ", string.Empty);
</code>
Something like that should do the trick, and is localized!
That's a rendering issue. Certainly multiplying by 100 to get cents will do the job.
The United States uses the decimal point to separate dollars from cents. But not all countries do that. Your "multiply by 100" solution is only correct for currencies that use 100 fractional units to represent a single whole. (Not the case in Japan for yen.)
If it is that simple, just do String.Replace('.','');
if you know that the values will always have 2 Decimal Positions then do this it's very simple
var strVar = 1234.56;
var somevalues = string.Format("{0:######}", strVar * 100);
output = 123456

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.

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