Currently, I'm retrieving data from a SharePoint Site, and I'm able to do so, however, I want limit the decimal place to 0.
if (item["ows_Amount_x0020__x0028_LC_x0029_"] != null)
{
str.AppendLine("<td bgcolor='#FFFFFF';align='right';> " + item["ows_Amount_x0020__x0028_LC_x0029_"].ToString() + "</td>");
}
Use a standard number format string in the ToString() method of Decimal (or Double, or whatever the actual datatype is of your item):
Convert.ToDecimal(item["ows_Amount_x0020__x0028_LC_x0029_"]).ToString("N0");
The "N0" here means "Number" at 0 decimal places. If you don't want commas added, use "F0" instead.
Number format reference: MSDN
Well, it depends on the type of: item["ows_Amount_x0020__x0028_LC_x0029_"]
Assuming it is always an amount that happens to be a string such as: 56.78
Then you can use:
if (item["ows_Amount_x0020__x0028_LC_x0029_"] != null)
{
decimal temp = 0;
if (decimal.TryParse(item["ows_Amount_x0020__x0028_LC_x0029_"], out temp))
str.AppendLine(" " + (long) temp + "");
else
str.AppendLine(" " + item["ows_Amount_x0020__x0028_LC_x0029_"].ToString() + "");
}
Try this
Convert.ToDecimal(item["ows_Amount_x0020__x0028_LC_x0029_"]).ToString("N1") //1 decimal place
OR
Convert.ToDecimal(item["ows_Amount_x0020__x0028_LC_x0029_"]).ToString("N0") //No decimal
OR
String.Format("{0:N1}", item["ows_Amount_x0020__x0028_LC_x0029_"]);
Related
According to the SQL queries below, I need to get a number value 2083.10, but when try to use the code to get int value from dbreader, it will be only 2083. the demical were gone.
string SQLCash = #"SELECT sum(t2.Cash-Change) AS Cash
FROM dbFBHdr t1, dbFBCollection t2
WHERE t1.Branch = t2.Branch
AND t1.CashNo = t2.CashNo
AND t1.CashDate >= '" + PDC.DateFrom + "' " +
"AND t1.CashDate <= '" + PDC.DateTo + "' " +
"AND t1.Status = 'CLOSED'";
FbCommand cmdCASH = new FbCommand(SQLCash, FbCon);
cmdCASH.ExecuteNonQuery();
FbDataReader readerCASH = cmdCASH.ExecuteReader();
while (readerCASH.Read() == true)
{
if (readerCASH["Cash"].ToString() == "")
{
PDC.CASH = "0";
}
else
{
PDC.CASH += String.Format("{0:n}",readerCASH["Cash"]);
PDC.TOCASH = readerCASH.GetInt32(readerCASH.GetOrdinal("Cash"));
}
}
And This is the code which I use it to get Int value from SQL
PDC.TOCASH = readerCASH.GetInt32(readerCASH.GetOrdinal("Cash"));
Since you need to Gets the value as a Decimal object, You need to use SqlDataReader.GetDecimal(Int32) method instead:
readerCASH.GetDecimal(readerCASH.GetOrdinal("Cash"));
Because the GetInt32 method will get the value as a 32-bit signed integer. Also you need to change the TOCASH's type to decimal. Also you should always use parameterized queries to avoid SQL Injection. Something like this:
AND t1.CashDate >= #DateFrom
yourCommand.Parameters.AddWithValue("#DateFrom", PDC.DateFrom);
//And other parameters also
Although specify the type directly and use the Value property is better than AddWithValue. See this https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/
Don't use GetInt32 if you want to get value as decimal, use GetDecimal
PDC.TOCASH = readerCASH.GetDecimal(readerCASH.GetOrdinal("Cash"));
You are formatting it to be without commas so it will be return as it is integer
PDC.CASH += String.Format("{0:n2}",readerCASH["Cash"]);
n2 means 2 digits after comma also i suggest you to use {0:c2} if you are working with currency
If you not sure to which .Net type will be mapped initial RDBMS one (e.g. Number(16, 4) -> ? will it be Single, Double or Decimal?) you can try converting:
decimal result = Convert.ToDecimal(readerCASH["Cash"]);
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());
}
I am using this code to type the currency amounts in a textbox with comma seperators and points. While typing numbers should display like this format(1,258,891.50). My code is working bt I can't type points. Its accepting only full numbers. Below is my code....
if (textBox5.Text == "")
return;
int n = textBox5.SelectionStart;
decimal text = Convert.ToDecimal(textBox5.Text);
textBox5.Text = String.Format("{0:#,###0}", text);
textBox5.SelectionStart = n + 1;
If your CurrentCulture has already , as a NumberGroupSeparator and . as a NumberDecimalSeparator, you can use The ("N") format specifier as N2 like;
textBox5.Text = text.ToString("N2");
If it is not, you can Clone your CurrentCulture, set these values to your properties and use that culture as a second parameter in ToString method.
var clone = (CultureInfo)CultureInfo.CurrentCulture.Clone();
clone.NumberFormat.NumberGroupSeparator = ",";
clone.NumberFormat.NumberDecimalSeparator = ".";
textBox5.Text = text.ToString("N2", clone); // 1,258,891.50
Your string format "{0:#,###0}" is not specifying any decimal places, so it is converting it without any decimal places. (Also the 0 at the end is actually doing nothing.)
Try this instead:
textBox5.Text = String.Format("{0:#,###.##}", text);
If for some reason you really do want to force a 0 at the end, try this:
textBox5.Text = String.Format("{0:#,###.#\\0}", text);
textBox5.Text = string.Format("{0:#,##0.00}", double.Parse(textBox5.Text));
Is there a way to convert a string to decimal in C# but ignoring trailing "garbage"? i.e. like PHP's floatval() or C strtod() ?
e.g.
Convert string "2974.23abcdefs" to decimal 2974.23
As others have mentioned, there is no exact, like for like, replacement for what you can do in PHP and I think, for good reason. In the scenario of a web application, I'm not really sure that if I were accepting a decimal with garbage at the end, I'd actually want to consider that as valid data but this is just my opinion.
What you can do is define a regular expression that would capture the decimal and recognise that this is happening. I find this much safer and reliable.
Obviously, the regular expression can be improved but this is a simple example for you: -
var match = Regex.Match("2974.23abcdefs", "^([0-9]+\\.[0-9]+)(.+)?$");
if (match.Success)
{
// See the also the link below for using Decimal.TryParse
Console.WriteLine(Convert.ToDecimal(match.Groups[1].Value));
}
See https://msdn.microsoft.com/en-us/library/system.decimal.tryparse%28v=vs.110%29.aspx for my preferred way to convert to a decimal. This would ensure that you are coping with the output of the regular expression for how Decimal is comprised
For more information on regular expressions, see https://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex%28v=vs.110%29.aspx
This works but only takes care of digits and the current culture's decimal-separator:
string input = "2974.23abcdefs";
decimal d;
char decSep = NumberFormatInfo.CurrentInfo.NumberDecimalSeparator[0]; // there is no culture with a decimal-separator that has more than one letter so this isn't harmful
if(!string.IsNullOrEmpty(input) && Char.IsDigit(input[0]))
{
string number = string.Concat(input.TakeWhile(c => Char.IsDigit(c) || decSep == c));
bool validDecimal = decimal.TryParse(number, out d);
Console.WriteLine("Valid? {0} Parsed to: {1}", validDecimal, d);
}
Since we are using , as decimal separator here in germany i get a different result than people who use . as separator. You get 2974.23 and i get 2974.
As a first, second, third try, this should go:
static double Parse(string str, IFormatProvider provider = null)
{
if (str == string.Empty)
{
return 0;
}
if (provider == null)
{
provider = CultureInfo.CurrentCulture;
}
NumberFormatInfo nfi = NumberFormatInfo.GetInstance(provider);
// [ws][sign][integral-digits[,]]integral-digits[.[fractional-digits]][E[sign]exponential-digits][ws]
string ws = #"\s*";
string sign = #"(" + Regex.Escape(nfi.PositiveSign) + "|" + Regex.Escape(nfi.NegativeSign) + ")?";
string integralDigits1 = "([0-9](" + Regex.Escape(nfi.NumberGroupSeparator) + ")*)*";
string integralDigits2 = "[0-9]+";
string fractionalDigits = "(" + Regex.Escape(nfi.NumberDecimalSeparator) + "[0-9]*)?";
string exponentialDigits = "([Ee]" + sign + "[0-9]+)?";
var rx = new Regex(ws + sign + integralDigits1 + integralDigits2 + fractionalDigits + exponentialDigits);
string match = rx.Match(str).ToString();
if (match == string.Empty)
{
return 0;
}
return double.Parse(match, provider);
}
Note that the composed regex is very complex, because there are various "parts" in a full double that has been written to a string.
From MSDN:
[ws][sign][integral-digits[,]]integral-digits[.[fractional-digits]][E[sign]exponential-digits][ws]
Still some numbers will crash this function, if they are too much big. So passing new string('9', 1000) will make the double.Parse throw an exception.
Use it like:
double num = Parse(" +1,0.1234E+12abcdefgh", CultureInfo.InvariantCulture);
or
double num = Parse(" +1,,,,,0.1234E+12abcdefgh");
(if you don't need to configure the culture, will use the CultureInfo.CurrentCulture)
There are many ways to do so. I suggest using a Regex first, and then decimal.TryParse().
This is a regex that grabs a floating point number at the begin of the string, like -123.43 or just 1234.56 or 123456:
^([+-][0-9]+\.?[0-9]*).*$
Putting this into C# looks like this:
// Step 1: Getting some input
String input = "123.4533wefwe";
// Step 2: Get rid of the trail
Regex r = new Regex(#"^([+-][0-9]+\.?[0-9]*).*$", RegexOptions.IgnoreCase);
MatchCollection matches = r.Matches(input);
if (matches.Count > 0) {
Match match = matches[0];
GroupCollection groups = match.Groups;
// Step 3: create a real decimal from the string
decimal i;
NumberStyles style;
CultureInfo culture;
style = NumberStyles.Number;
culture = CultureInfo.CreateSpecificCulture("en-GB");
String matchedNumber = groups[1].Value;
if (decimal.TryParse(matchedNumber, style, culture, out i)) {
// Step 4: giving back the result:
Console.WriteLine("Parsed decimal: " + i);
}
}
The output of this is:
Parsed decimal: 123.4533
Remark: All this seems to become a bigger problem if you would like to parse real floating point number literals that include exponential notation. Then, severals stages of casting would be necessary.
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