convert this string into decimal - c#

Sounds easy but when I tried to achieve i'm stock about how is the formatter to make this conversion this are some examples of strings that i need to convert to decimal
00.24
48.34
01.24
Does anybody know how can i Accomplish this?? I tried like this
try
{
decimal x = Convert.ToDecimal("00.24", );
//Which formatter do I need to pass??
decimal x = Convert.ToDecimal("00.24", Formatter???);
}
Catch(Exception e)
{
throw new Exception()
}
But It doesn't work because the result it's 24D and i need 0.24D

I suspect your system culture is not English and has different number formatting rules. Try passing the invariant culture as the format provider:
decimal d = Convert.ToDecimal("00.24", CultureInfo.InvariantCulture);
You could also use Decimal.Parse:
decimal d = Decimal.Parse("00.24", CultureInfo.InvariantCulture);

Why not just use Decimal.Parse
decimal x = Decimal.Parse("00.24");
Console.WriteLine(x); // Prints: 00.24

I think Decimal.TryParse should work. More info here.

The result you're getting is because the dot . is tretaed as a group (thousand) separator. the parser simply discards it, and doesn't check if the group sizes are right. So '20.100.200' or '1.2.3.4' would also get parsed as 20100200 and 1234.
This happens on many european cultures, like 'es'
You have to use any culture that doesn't consider a . as a group separator, but as a decimal separator. CultureInfo.InvariantCulture is one of the possible cultures (it has basically the same configuration of en-US).

Related

How can i Convert string to decimal

I can not convert from string into decimal this is the value of lblTotal="110,00€"
I want to convert it to decimal how can I convert it?
decimal number;
if( Decimal.TryParse(((Label)e.Item.FindControl("lblTotal")).Text.ToString(), out number))
{
}
If you can't parse your string, there can be a few possibilities..
First of all, Decimal.TryParse uses NumberStyles.Number style and this does not includes Currency style. Both are composite styles. That's why you need to use another overload that specify currency symbol and decimal separator.
Second, your Decimal.TryParse uses CurrentCulture settings by default. That means, your CurrencySymbol is not € and/or your NumberDecimalSeparator is not ,.
As a best solution, you can Clone your CurrentCulture and set these properties with Currency style like;
var clone = (CultureInfo) CultureInfo.CurrentCulture.Clone();
clone.NumberFormat.CurrencySymbol = "€";
clone.NumberFormat.NumberDecimalSeparator = ",";
decimal number;
if(decimal.TryParse(((Label)e.Item.FindControl("lblTotal")).Text,
NumberStyles.Currency, clone, out number))
{
// You can use number here
}
You should inform the Decimal.TryParse that you have a currency symbol and what is your culture
string test = "110,00€";
if( Decimal.TryParse(test, NumberStyles.Currency, CultureInfo.CurrentCulture, out number))
{
Console.WriteLine(number);
}
I would also recommend to use a more defensive approach to your retrieving of the label to parse.
Label lbl = e.Item.FindControl("lblTotal") as Label;
if(lbl != Null)
{
.....
}
You can use CultureInfo.CreateSpecificCulture with culture code of Countries using Euro as currency.
Table of Language Culture Names, Codes, and ISO Values Method.
for example Greece, Ireland, Italy uses this currency.
Simply
decimal resault = decimal.Parse(((Label)e.Item.FindControl("lblTotal")).Text.ToString()
,NumberStyles.Currency
,CultureInfo.CreateSpecificCulture("it-IT"));
This will convert your string "110,00€" to decimal correctly Since Italy uses euro(€) as currency.
Or you can use another Culture by searching in the provided link.

How to prevent decimal.TryParse convert "," to "."?

This is my code:
string myValue = "0,203";
decimal.TryParse(myValue, NumberStyles.Any, CultureInfo.CurrentCulture, out myValueAsDecimal;
...
myValueAsDecimal is 0.203 now
Is it possible that myValueAsDecimal has 0,203 after TryParse or the internal representation of decimal is always 0.203 and I need to format GUI output if I need 0,203?
Is it possible that myValueAsDecimal has 0,203 after TryParse
No. It's just a number - it has no concept of a text format. To think about it another way with a simpler type, consider these two lines of code:
int x = 0x100;
int y = 256;
Are those two values the same? Yes, they represent the same number. If you convert the values of x and y to strings, by default they will both end up as "256" - but they could both end up as "100" if you request a hex representation.
It's important to distinguish between the real value of a variable and a textual representation. Very few types (none that I can think of immediately) carry around information about a textual representation with them - so for example, a DateTime can be parsed from a variety of formats, but has no "memory" of an original text format. It's just a date and time, which could then be formatted according to any format.
If you need to maintain the idea of "a decimal number and the culture in which it was originally represented" then you should create your own class or struct for that pairing. It's not present in decimal itself.
decimal d = 0.203m;
Console.WriteLine(d.ToString(CultureInfo.InstalledUICulture));
Console.WriteLine(d.ToString(CultureInfo.InvariantCulture)); // decimal point: dot
Console.WriteLine(d.ToString(CultureInfo.GetCultureInfo("en-US"))); // default decimal point: dot
Console.WriteLine(d.ToString(CultureInfo.GetCultureInfo("ru-RU"))); // default decimal point: comma
Result:
0,203
0.203
0.203
0,203
Looks like your CurrentCulture has , as a NumberDecimalSeparator and that's why your parsing succeed.
Actually, 0.203 and 0,203 are the same as value. Only matter is their textual representation when you print it.
If you wanna get your value as a 0,203 representation, you can use a culture that has , as a NumberDecimalSeparator.
For example, my culture (tr-TR) has a ,. When you represent your decimal with it, you will get 0,203.
string myValue = "0,203";
decimal myValueAsDecimal;
decimal.TryParse(myValue, NumberStyles.Any, CultureInfo.CurrentCulture, out myValueAsDecimal);
myValueAsDecimal.ToString(new CultureInfo("tr-TR")).Dump(); // 0,203
The value of the Decimal is the same regardless of the Culture, it's
0.203
what changes is its String representation (decimal separator in your case), so
if you want to change decimal separator and don't want to change the Culture
you can just assign NumberDecimalSeparator in your custom NumberFormatInfo e.g.
Decimal d = 0.203M;
NumberFormatInfo myNumberInfo = new NumberFormatInfo() {
NumberDecimalSeparator = "," // Comma, please
};
String result = d.ToString(myNumberInfo); // "0,203"

Converting Request QueryString to Decimal

I can not convert query string to decimal.
In this example, when I control Request.QueryString["Amount"] value, It is 32.52 After the below code works, The Amount values is 3252M like that. How can I easily do this?
decimal Amount= 0;
if (Request.QueryString["Amount"] != null)
Amount = Convert.ToDecimal(Request.QueryString["Amount"]);
Convert.ToDecimal uses your current culture settings by default.
I strongly suspect your CurrentCulture's NumberDecimalSeparator property is not ., but NumberGroupSeparator property is .
That's why your program thinks this is a thousands separator, not decimal separator and it parses as a 3252, not 32.52.
As a solution you can use a culture which have . as a NumberDecimalSeparator like InvariantCulture, or you can .Clone your current culture and set it's NumberDecimalSeparator to . 1
Amount = Convert.ToDecimal(Request.QueryString["Amount"], CultureInfo.InvariantCulture);
or
var culture = (CultureInfo)CultureInfo.CurrentCulture.Clone();
culture.NumberFormat.NumberDecimalSeparator = ".";
culture.NumberFormat.NumberGroupSeparator = ",";
Amount = Convert.ToDecimal("32.52", culture);
1: If your current culture's thousands separator is not . already. Otherwise, you need to change it as well. Both property can't have the same values for any culture
I think you are having problems with the Culture as stated in the rpevious answer. You may want to try using different cultures:
RetVal = decimal.Parse(Request.QueryString["Amount"], CultureInfo.CurrentCulture);
Then I would try:
RetVal = decimal.Parse(Request.QueryString["Amount"], CultureInfo.InvariantCulture);

Convert from exponential notation to non-exponential notation

I have tried:
MessageBox.Show(System.Numerics.BigInteger.Parse("7.56e+011",
NumberStyles.Float,
CultureInfo.InvariantCulture));
But it continues to show 7.56e+011
You are looking to format the number. You can use String.Format to do so
string.Format("{0:F}",System.Numerics.BigInteger.Parse("7.56e+011",
NumberStyles.Float,
CultureInfo.InvariantCulture))
Running the following code
Gives you the following MessageBox
you can specify no decimal points by changing it to {0:F0} for the format.
Try
BigInteger num = System.Numerics.BigInteger.Parse("7.56e+011",
NumberStyles.Float,
CultureInfo.InvariantCulture);
String text = num.ToString("F5"); // New format string, here with 5 digits.
Your solution does an implicit conversion from BigInteger back to string again, which uses the scientific notation if the exponent is large.
decimal dec = decimal.Parse("7.7583877127496407E-6",
System.Globalization.NumberStyles.Any);
Console.WriteLine(dec);

c# double.parse() to always use a . period not comma

How can I specify that my decimal.Parse must always expect to receive a string with a '.' like "4.75" no mater what the system settings of the computer are?
I am reading in a file from excel and it gives me value with a '.' and I see that if I run my program on my laptop It throws and error as it expects a ','
I can use:
string tmp1 = tmp[2].Replace('.', ',');
but then obviously if my computer wants a ''. then it will give an error.
What is my best option?
See: Double.Parse
Use this overload to specify an IFormatProvider in your case CultureInfo.InvariantCulture.
var value = double.Parse(tmp[2], CultureInfo.InvariantCulture);
However I would recommend Double.TryParse if you intend to make your process durable.
double value;
if(!double.TryParse(tmp[2],
NumberStyles.None,
CultureInfo.InvariantCulture,
out value))
{
// error handling
}
Use Double.Parse Method (String, IFormatProvider) with CultureInfo.InvariantCulture for parsing.
double d = double.Parse("2.2", CultureInfo.InvariantCulture);
You could use the overload of Decimal.Parse which will allow you to specify a culture:
decimal value = decimal.Parse(tmp[2], CultureInfo.InvariantCulture);

Categories