I am using Convert.ToDecimal in linq, sometime amount value contains dot (.) as user want to write .50 or similar, as soon as they enter dot (using Numeric keypad from mobile), code is getting executed and throwing an exception.
I am getting string is not correct format exception for below code
var enteredAmountInTenders = TenderListCollection.Sum(x => Convert.ToDecimal(string.IsNullOrEmpty(x.Amount) ? "0" : x.Amount));
How can I ignore dot for above code and just get 0?
I would use decimal.TryParse instead of Convert.ToDecimal to cast the value.
var enteredAmountInTenders = TenderListCollection
.Sum(x => !decimal.TryParse(x.Amount,out var result) ? 0 : result);
you could check this before your set your property for the object in your TenderListCollection.
private string _amount = "0";
public string Amount
{
get
{
return _amount;
}
set
{
if(!string.IsNullOrEmpty(value))
{
if(value != ".")
{
_amount = value;
}
}
}
}
In general i dont like storing amounts as string, so i also would suggest to rename the Amount to GivenAmount and have an Amount Property which is a decimal, this way our code is clean and you dont need to parse in a Lambda expression.
_item = new OutTYonetimOzet();
_item.Banka = Convert.ToDecimal(" ");
liste.Add(_item);
There is a list called liste. In List item Banka named element is decimal value. I want to show the empty string when I show it on the screen. But this code is getting an error that can not be cast. What is the problem.
Error message is:
Input string was not in a correct format.
There's no such thing as a "blank decimal". decimal cannot have a value that is "blank" - it always has a numeric value. Convert.ToDecimal(" ") is nonsensical - there is nothing it can return that makes sense.
You could try using a Nullable<decimal> (aka decimal?) perhaps; i.e.
public decimal? Banka {get;set;}
and
_item.Banka = null;
You can also use the decimal.TryParse instead of Convert. With this technique you can check if the string is valid.
_item = new OutTYonetimOzet();
decimal val = decimal.MinValue;
if (decimal.TryParse(" ", out val))
{
_item.Banka = val;
}
else
{
//your default goes here
_item.Banka = 0;
}
liste.Add(_item);
and as Mark suggested I would use Nullable<decimal> and use null as default value.
I have a string value and need to convert that to decimal.
var str = null;
decimal number;
decimal d = Decimal.TryParse(str, out number) ? number : 0M;
It's working fine.
Now I am trying to achieve the same thing by using the new Null-Conditional Operator of C# 6.0 . How can I do so?
I know it's a wrong attempt.
var str = null;
decimal d = str?.Convert.ToDecimal(str);
A blank (empty) string is not null, so you can't use that operator.
You could do:
decimal d = string.IsNullOrEmpty(str) ? 0M : Convert.ToDecimal(str);
EDIT: OK, now we're starting with a null string. In which case...
decimal d = (str == null) ? 0M : Convert.ToDecimal(str);
I still don't think that this is an appropriate time to use the null-conditional operator, because that's most useful when the ultimate result of the expression can be null - which is not true in your case.
According to msdn you can't do that as null conditional operator is:
Used to test for null before performing a member access (?.) or index
(?[) operation
and in this case you aren't indexing or accessing the input string members.
As the other answer stated the way to do that would be
decimal d = String.IsNullOrEmpty(str) ? default(decimal) : Convert.ToDecimal(str);
Not exactly answering the question, but I would create an extension method where you have the advantage of being able to formally call it on null values too.
This implementation gives the correct double if the input string is in a valid format (using the default formatting), and gives the optionally passed default value if string is null or empty or is in incorrect format.
public static double ConvertToDoubleOrDefault(this string input, double def = 0.0)
{
if (string.IsNullOrEmpty(str)) return def;
double result;
if (!double.TryParse(str, out result)) return def;
return result;
}
....
string test = "1234";
string test2 = null;
var d = test.ConvertToDoubleOrDefault(); // => 1234
d = test2.ConvertToDoubleOrDefault(); // => 0.0
I need help figuring out how to assign a string to a double.
double value = "myString";
I have double value = double.Parse("myString"); but this throws a FormatException.
I have trying to concatenate like this:
string stringValue += doubleValue.toString() + intValue.ToString;
return stringValue;
I have double value = double.Parse("myString"); but this throws a string.Format error.
Yes, that's the behaviour you want in this case. "myString" doesn't have a numerical value, so the correct numerical value to give it, is to throw a formatting error.
double.Parse("1.2") would work or not depending on whether the culture in use was one where 1.2 was represented as "1.2" or as "1,2". double.Parse("1.2", CultureInfo.InvariantCulture) will always return 1.2, because it's specific about which culture to use.
double.TryParse is useful where it's likely for someone to pass an inappropriate string (like "myString") because it returns a boolean representing success or failure, rather than throwing an exception.
You can use TryParse
string x = "1234";
double y;
if(double.TryParse(x, out y))
{
Console.WriteLine("success y = " + y.ToString());
}
else
{
Console.WriteLine(x + " could not be converted to a double");
}
Parse it, assuming myString is a valid double string representation (eg "3.49", "1394.293", "-1.30E3")
double value = double.Parse(myString)
Most (All?) of the normal numerical types have parse methods. Use TryParse if you're unsure if it's valid (Trying to parse "abc" as a number will throw an exception)
#L.B For custom parsing you can define a NumberFormatInfo like this:
var a = new System.Globalization.NumberFormatInfo()
a.NumberDecimalSeparator = ",";
a.NumberGroupSeparator = ".";
double d = Double.Parse("1.000.000,5", a);
You cannot assign a string to a double. It's impossible. A double is a numerical type. A string is not.
If you parse a string that is a double it is possible.
var doubleThing = Double.Parse("9.99");
double.Parse(string);
Can and will through an exception if the format is incorrect. What are you trying to parse?
double.TryParse("1.05", out value);
Will return true or false if the parse succeeds or fails.
How do I format a Double to a String in C# so as to have only two decimal places?
If I use String.Format("{0:0.00}%", myDoubleValue) the number is then rounded and I want a simple truncate without any rounding. I also want the conversion to String to be culture sensitive.
I use the following:
double x = Math.Truncate(myDoubleValue * 100) / 100;
For instance:
If the number is 50.947563 and you use the following, the following will happen:
- Math.Truncate(50.947563 * 100) / 100;
- Math.Truncate(5094.7563) / 100;
- 5094 / 100
- 50.94
And there's your answer truncated, now to format the string simply do the following:
string s = string.Format("{0:N2}%", x); // No fear of rounding and takes the default number format
The following rounds the numbers, but only shows up to 2 decimal places (removing any trailing zeros), thanks to .##.
decimal d0 = 24.154m;
decimal d1 = 24.155m;
decimal d2 = 24.1m;
decimal d3 = 24.0m;
d0.ToString("0.##"); //24.15
d1.ToString("0.##"); //24.16 (rounded up)
d2.ToString("0.##"); //24.1
d3.ToString("0.##"); //24
http://dobrzanski.net/2009/05/14/c-decimaltostring-and-how-to-get-rid-of-trailing-zeros/
I suggest you truncate first, and then format:
double a = 123.4567;
double aTruncated = Math.Truncate(a * 100) / 100;
CultureInfo ci = new CultureInfo("de-DE");
string s = string.Format(ci, "{0:0.00}%", aTruncated);
Use the constant 100 for 2 digits truncate; use a 1 followed by as many zeros as digits after the decimal point you would like. Use the culture name you need to adjust the formatting result.
i use price.ToString("0.00")
for getting the leading 0s
Simplest method, use numeric format strings:
double total = "43.257"
MessageBox.Show(total.ToString("F"));
The c# function, as expressed by Kyle Rozendo:
string DecimalPlaceNoRounding(double d, int decimalPlaces = 2)
{
double factor = Math.Pow(10, decimalPlaces);
d = d * factor;
d = Math.Truncate(d);
d = d / factor;
return string.Format("{0:N" + Math.Abs(decimalPlaces) + "}", d);
}
How about adding one extra decimal that is to be rounded and then discarded:
var d = 0.241534545765;
var result1 = d.ToString("0.###%");
var result2 = result1.Remove(result1.Length - 1);
I had that problem with Xamarin Forms and solved it with this:
percent.ToString("0.##"+"%")
This is working for me
string prouctPrice = Convert.ToDecimal(String.Format("{0:0.00}", Convert.ToDecimal(yourString))).ToString();
I know this is a old thread but I've just had to do this. While the other approaches here work, I wanted an easy way to be able to affect a lot of calls to string.format. So adding the Math.Truncate to all the calls to wasn't really a good option. Also as some of the formatting is stored in a database, it made it even worse.
Thus, I made a custom format provider which would allow me to add truncation to the formatting string, eg:
string.format(new FormatProvider(), "{0:T}", 1.1299); // 1.12
string.format(new FormatProvider(), "{0:T(3)", 1.12399); // 1.123
string.format(new FormatProvider(), "{0:T(1)0,000.0", 1000.9999); // 1,000.9
The implementation is pretty simple and is easily extendible to other requirements.
public class FormatProvider : IFormatProvider, ICustomFormatter
{
public object GetFormat(Type formatType)
{
if (formatType == typeof (ICustomFormatter))
{
return this;
}
return null;
}
public string Format(string format, object arg, IFormatProvider formatProvider)
{
if (arg == null || arg.GetType() != typeof (double))
{
try
{
return HandleOtherFormats(format, arg);
}
catch (FormatException e)
{
throw new FormatException(string.Format("The format of '{0}' is invalid.", format));
}
}
if (format.StartsWith("T"))
{
int dp = 2;
int idx = 1;
if (format.Length > 1)
{
if (format[1] == '(')
{
int closeIdx = format.IndexOf(')');
if (closeIdx > 0)
{
if (int.TryParse(format.Substring(2, closeIdx - 2), out dp))
{
idx = closeIdx + 1;
}
}
else
{
throw new FormatException(string.Format("The format of '{0}' is invalid.", format));
}
}
}
double mult = Math.Pow(10, dp);
arg = Math.Truncate((double)arg * mult) / mult;
format = format.Substring(idx);
}
try
{
return HandleOtherFormats(format, arg);
}
catch (FormatException e)
{
throw new FormatException(string.Format("The format of '{0}' is invalid.", format));
}
}
private string HandleOtherFormats(string format, object arg)
{
if (arg is IFormattable)
{
return ((IFormattable) arg).ToString(format, CultureInfo.CurrentCulture);
}
return arg != null ? arg.ToString() : String.Empty;
}
}
To what is worth, for showing currency, you can use "C":
double cost = 1.99;
m_CostText.text = cost.ToString("C"); /*C: format as currentcy */
Output: $1.99
You could also write your own IFormatProvider, though I suppose eventually you'd have to think of a way to do the actual truncation.
The .NET Framework also supports custom formatting. This typically involves the creation of a formatting class that implements both IFormatProvider and ICustomFormatter. (msdn)
At least it would be easily reusable.
There is an article about how to implement your own IFormatProvider/ICustomFormatter here at CodeProject. In this case, "extending" an existing numeric format might be the best bet. It doesn't look too hard.
Following can be used for display only which uses the property of String ..
double value = 123.456789;
String.Format("{0:0.00}", value);
Solution:
var d = 0.123345678;
var stringD = d.ToString();
int indexOfP = stringD.IndexOf(".");
var result = stringD.Remove((indexOfP+1)+2);
(indexOfP+1)+2(this number depend on how many number you want to
preserve. I give it two because the question owner want.)
Also note the CultureInformation of your system. Here my solution without rounding.
In this example you just have to define the variable MyValue as double.
As result you get your formatted value in the string variable NewValue.
Note - Also set the C# using statement:
using System.Globalization;
string MyFormat = "0";
if (MyValue.ToString (CultureInfo.InvariantCulture).Contains (CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator))
{
MyFormat += ".00";
}
string NewValue = MyValue.ToString(MyFormat);