Convert.ToDecimal doesn't convert input decimal number - c#

I'm new to c# and tried to convert the input into decimal and double. It works fine when I enter an intiger but stops immediately when I enter a decimal or double number and gives me an "Exception Unhandeled" Error message.
My code:
Console.Write("Enter number: ");
decimal d = Convert.ToDecimal(Console.ReadLine());
Console.WriteLine(d);
So when I enter 3 the program prints out the number 3. But if I enter 3.6, it stops.
I've seen another solution using Double.Parse(); but still can't make my code work.
Console.Write("Enter number: ");
decimal d = Decimal.Parse(Console.ReadLine());
Console.WriteLine(d);
In my codes I'm using decimal but the same applies to double.
I've tried to look up other questions like this (stackoveflow, google), I've checked out the documentation but couldn't find the issue.
What's wrong with my code?

All string conversion operations use the current culture, which may differ in things like decimal or thousands separator and other things. You can specify the invariant culture in any of these conversions:
decimal d = Convert.ToDecimal(Console.ReadLine(), CultureInfo.InvariantCulture);
decimal d = Decimal.Parse(Console.ReadLine(), CultureInfo.InvariantCulture);
Another option is to set the default culture at the start of your application, which will affect all future conversions:
CultureInfo.CurrentCulture = CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture;

Well, if you use decimal for finance you may want to accept not only decimal separator, but group (thousand) one:
123,456,789.45
here . is a decimal separator when , are group ones. To support group separator you can specify NumberStyles.Any
Console.Write("Enter number: ");
decimal d;
while (!Decimal.TryParse(Console.ReadLine(), NumberStyles.Any, null, out d))
Console.WriteLine("Invalid syntax. Please, try again.");
Please, note that here I've put null that stands for CultureInfo.CurrentCulture which at your workstation seems has , for decimal separator and . for group one:
"123.45" -> 12345m - note, that group separator(s) is/are removed
"1.2.3.4.5" -> 12345m
"123,45" -> 123.45m - while decimal is turned into decimal point
If you want to treat . as a decimal separator (so "123.45" will be parsed into 123.45m), you can specify CultureInfo.InvariantCulture:
Console.Write("Enter number: ");
decimal d;
while (!Decimal.TryParse(Console.ReadLine(),
NumberStyles.Any,
CultureInfo.InvariantCulture,
out d))
Console.WriteLine("Invalid syntax. Please, try again.");

As was mentioned in comments, a decimal separator is varying from country to country. I would suggest to manual replace the entered symbol to the separator used in your culture:
string separator = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
decimal d = Decimal.Parse(Console.ReadLine().Replace(".", separator).Replace(",", separator));

Related

Decimal point lost in conversion

I have a string that contains: 2.53 and I'm trying to convert this number into decimal type, so I did:
string value = "2.53";
decimal converted = Convert.ToDecimal(value);
but the final result is: 253
Decimal point is different in every culture. In your culture it might be a comma. You can use InvariantCulture which has dot as decimal separator:
decimal converted = Convert.ToDecimal(value, CultureInfo.InvariantCulture);

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.

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);

How to Convert Number to Currency Format using WPF and C#.net [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Convert string value to decimal with thousand seperator?
This might be a very simple question.
I want a Convert number to Currency Format.
Double number = 1000000.00;
Convert to
String Strnumber = 10,00,000.00;
Any Idea?..................
But it shows only number not a currency Name
Use the Cformat specifier for currency.
Double number = 1000000.00;
String output = number.ToString("C2");
The Currency ("C") Format Specifier
Demo
Edit: If you don't want a currency-symbol as commented you can use the overload of ToString with the FormatProvider. Then pass a custom NumberFormatInfo without symbol:
var culture = CultureInfo.CurrentCulture;
var mutableNfi = (NumberFormatInfo) culture.NumberFormat.Clone();
mutableNfi.CurrencySymbol = "";
String output = number.ToString("C2", mutableNfi);
decimal value = 16325.62m;
string specifier;
specifier = "N";
Console.WriteLine("{0}: {1}", specifier, value.ToString(specifier));
// Displays: N: 16,325.62
From the required output it seems like you are using the indian number grouping system.
The following should provide you with the value formated in Lakh/Crore etc.
Double number = 1000000.00;
Console.WriteLine(String.Format(new System.Globalization.CultureInfo("en-IN"), "{0:C2}", number));
It should output
10,00,000.00
If you want to display the number without the currency symbol. You can either reformat the number using N general number specifier. The only issue to consider is how you would like the negative numbers displayed. eg,
Double number = 1000000.00;
Console.WriteLine(String.Format(new System.Globalization.CultureInfo("en-IN"), "{0:N2}", number));
Or you can replace the currency symbol within the Number Format specifier. eg,
System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo("en-IN");
ci.NumberFormat.CurrencySymbol = "";
Console.WriteLine(String.Format(ci, "{0:N2}", number));
Both should output
10,00,000.00

convert this string into decimal

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).

Categories