C# string to decimal error - c#

I'm having trouble with a very simple problem. Basically I'm taking a string, like "$30.00", and removing the '$' and then trying to convert it to a decimal. Although I keep getting an error stating that the string isn't in the correct format. Not sure what to do from here...
string freightstart = PostFregihtAmount.ToString();
freightstart = freightstart.TrimStart('$');
decimal freight = Decimal.Parse(freightstart);
I tried the following, per Alex Skiba's suggestion in the comments:
Decimal.Parse(freightstart, System.Globalization.CultureInfo.InvariantCulture);
This is the error I receive upon debugging:
This is a plugin for our onsite CRM 2011 system and some fields that I have to reference on the quote form are currency fields. When I query the data they come back as string formats, hence the example "$30.00". Long story short I need to convert it to decimal so that I may do my tax solution.

Try explicitly allowing the decimal point when you parse the string, as well as the currency symbol (then you don't have to trim the $ before parsing):
var freight = Decimal.Parse("$30.00",
NumberStyles.AllowCurrencySymbol | NumberStyles.AllowDecimalPoint);

Related

Conversion of a currency string in the format "0.0 GBP 0"

I'm pulling data from an API and I'm trying to see if there is a decent way of pulling apart the string that's being returned.
Ideally I want to put this into a database as a decimal value.
UPDATE:
I'm interested in the 0.0 and I'd wondered if there was a decimal.parse that could strip it down like I could do with the date/time as noted below:
DateTime updated;
if (DateTime.TryParseExact("Wed Jun 05 08:06:17 UTC 2013",Config.dateTimeFormat,CultureInfo.InvariantCulture,DateTimeStyles.None,out updated))
{
// Yeah!!
}
However what has been noted below is that the trim and strip will do the job. What I'm really after is a high performance solution to the problem as it's part of a delta sync routine.
So you just want to parse the first part in the string which represents the numeric value? Then you could use String.Split and take the first:
string text = "0.0 GBP 0";
string value = text.Trim().Split()[0]; // 0.0
decimal pounds = decimal.Parse(value, CultureInfo.InvariantCulture);

Converting a Numeric value fetched from a Dataset to a String Asp.net c#?

I have a numeric value like this in my db,
14192555.00
when i get it and put it in text box and convert it in to string it results in,
this.txtPriorNYSDOTRating.Text = ds.Tables[0].Rows[0]["Fact2A_PriorNYSDOTPerfRatingScore"].ToString();
14192555.0000
for it formatting i also tried,
this.txtPriorNYSDOTRating.Text = ds.Tables[0].Rows[0]["Fact2A_PriorNYSDOTPerfRatingScore"].ToString("0.####");
it result in error "no overload for method string"
Hopes for your suggestion thanks in advance
EDITED:
i have date in database like,
2010-10-19 00:00:00.000
i get it like,
10/19/2010 12:00:00 AM
my code is,
this.txtDesignatedDate.Text =Convert.ToDateTime(ds.Tables[0].Rows[0]["DesignatedDate"]).ToString();
how to format it to get only `"10/19/2010"
Hopes for your reply
You need to convert it to double and then apply the format.
double d = Convert.ToDouble(ds.Tables[0].Rows[0]["Fact2A_PriorNYSDOTPerfRatingScore"]);
this.txtPriorNYSDOTRating.Text = d.ToString("0.####");
Currently it is of object type and that doesn't expose ToString overload with format parameter.

datetime.TryParseExact with different formats of values

I have a json string that contains the values for a datetime and a parsing mechanism that looks like this:
if (DateTime.TryParseExact(TheUserTimeString, "M.d.yyyy.HH.mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out TheUserTime))
{
TheObject.UserDateTime = TheUserTime;
}
The string TheUserTimeString is generated on the client. It can be 12.20.2011.13.21 and the code works fine but when it's 12.20.2011.13.2 the code breaks because the minutes are in one digit. And when the month is also in one digit... who knows.
What would be a better way to rewrite this parsing code so that the string gets parsed correctly every time.
Thanks for your suggestions.
Use the string "M.d.yyyy.HH.m", a single m denotes minutes without the leading 0. Source.
Your DateTime format string just needs to be: "M.d.yyyy.H.m".
This allows for months, days, hours and minutes to be expressed as single digit values.
See here for the MSDN page documenting the valid formats of this string for further information.

Formatting a String to be Converted to Double

I'm trying to convert a string to double. The incoming string is always going to be a whole number...no decimals. So, for example "90".
double percentToCheck = Convert.ToDouble(String.Format("{0:0.00}", SomeEntity.KeyIDs.SomePercentTrigger));
SomePercentTrigger is the % that I will be converting.
I get a "string is not in the correct format" error so how should I format this string? I've got to format it because if I don't I get the same error with just this during the conversion:
double percentToCheck = Convert.ToDouble(SomeEntity.KeyIDs.SomePercentTrigger);
UPDATED:
SomePercentTrigger is simply a string such as "80"..it'll always be a whole number too.
Update:
Your string is "52.0".
It must be the '.' that causes the FormatException.
You are probably on a machine where '.' is not set as the decimal point (e.g. I live in Germany and use German regional settings. Our decimal point is ',' )
To get around this problem you need to parse the string using CultureInfo.InvariantCulture.
var value = double.Parse(myString, CultureInfo.InvariantCulture);
InvariantCulture should be used for the parts of your application that revolve around data storage. Make sure you use it as well when converting doubles to strings Console.WriteLine(value.ToString(CultureInfo.InvariantCulture));
I suspect that SomeEntity.KeyIDs.SomePercentTrigger has some invalid characters in it (something other than digits, '.' and a optional leading '-'), say for example "80%"
So you're getting a FormatException on this line
double percentToCheck = Convert.ToDouble(String.Format("{0:0.00}", SomeEntity.KeyIDs.SomePercentTrigger));
because {0:0.00} formatting rules are only valid for numeric values.
Also you get the very same exception here:
double percentToCheck = Convert.ToDouble(SomeEntity.KeyIDs.SomePercentTrigger);
because "80%" can not be converted into a double.
You should either
put some logging right in front of the failing statement
or debug that code
and see what the actual content of SomeEntity.KeyIDs.SomePercentTrigger is.
Use double.Parse(string) or alternatively double.TryParse(string, out value)
It doesn't make sense to try to format a string. You would have to parse it to a number first in order to format it. Anyhow, there is no problem in parsing a number without decimals as a double, so the string is probably not containing what you think it does.
If the string contains a number in integer format, parse the string as an integer, and then convert the integer to a double:
double percentToCheck = (double)Int32.Parse(SomeEntity.KeyIDs.SomePercentTrigger);

Convert any currency string to double

I need to store multiple currencies in SQL server. I understand that SQL won't support all different types of currencies (unless I store it as a string, but I don't want to do that).
My idea was to convert all the values from their currency format to a standard double and store that instead. Then just re-format based on the culture info when displaying. However, I have tried doing something like e.g.
var cultureInfo = new System.Globalization.CultureInfo("en-US");
double plain = return Double.Parse("$20,000.00", cultureInfo);
This doesn't ever seem to work it always throws a FormatException. Even removing the currency symbol and just trying to do this based on the number alone does the same thing. This is just an example I want to support pretty much any type of currency.
Is there a standard way of stripping out currency and getting the value as a double?
I think this should work:
double.Parse(currencyValue, NumberStyles.AllowCurrencySymbol | NumberStyles.Currency);
Here you can see more about the NumberStyles.
Edit: In case anyone sees this answer without looking at the other answers/comments, this answer answered the question as written, but storing currency as a double is not a good idea, and it would be better to use decimal instead.
You should pass NumberStyles to the Parse function
Decimal.Parse("$20,000.00", NumberStyles.AllowCurrencySymbol | NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands, new CultureInfo("en-US"));
A few other things, for currencies I would suggest you use Decimal. And this might be way off, but it might be better to store the currency data as Money in the DB and add a currency code to identify the currency of the value.
Yes, and the answers suggestung NumberStyles.Currency that would be better. It is a pre-Or'd value, if you still think you want to use the strings.
You can also use the tryparse()
string input = "$2,000.00";
double parsed = 0d;
double.TryParse(input, NumberStyles.AllowCurrencySymbol | NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands, CultureInfo.CurrentCulture, out parsed))

Categories

Resources