System.FormatException if use new CultureInfo("id-ID") - Indonesian culture - c#

I am trying to convert exponential value to decimal with Indonesian culture but it does not work..
string _ex = "1.2162876E-5";
decimal _dec = decimal.Parse(_ex, NumberStyles.Float, new CultureInfo("id-ID"));
it thrown me System.FormatException
but it works properly if I use en-US
decimal d0 = decimal.Parse(_ex, NumberStyles.Float, new CultureInfo("en-US"));
what I missed?
please help
thanks a lot
Don2

In id-ID, the decimal separator (CultureInfo.NumberFormat.NumberDecimalSeparator) is ",", so it is expecting "1,2162876E-5" as the input (meaning the numeric value zero point zero zero zero zero one two etc). If the input is using a "." to mean decimal point, then you should probably use the invariant culture to parse it (CultureInfo.InvariantCulture), instead of a locale-specific culture.

Related

Converting string with many leading zeros to decimal

How can I convert string which looks like this:
0005.47
to decimal value 5.47.
This value is kept in newStringArray[1] so I did this: Convert.ToDecimal(newStringArray[1])
But as a result I got this value : 547
What's the point here?
Your culture settings think that a point is not the decimal separator but the thousands separator.
You need to pass the information about the culture you want to use to Convert.ToDecimal. It can be done passing the CultureInfo.InvariantCulture property to inform the converter to use the proper decimal symbol when converting.
string test = "0005.47";
decimal value = Convert.ToDecimal(test, CultureInfo.InvariantCulture);

How do I convert string to decimal?

I have this textbox that accepts numbers, commas, and periods.
Let's say this textbox contains input 14,500.00
I tried to convert this number to decimal with Convert.ToDecimal(textbox.text) but it's not working. Convert.ToDecimal() to textboxes that contain input that has the format XXXX.DD are converted to decimal but input with format X,XXX.DD or any input with a thousand separator results to error:
Input string was not in correct format
Is Convert.ToDecimal() appropriate in this case?
ADDITIONAL INFO:
Here is the form. If I click 'Add', the product of 'Price' and 'Quantity' should be displayed as 'Amount' in the datagridview.
The syntax in the 'Add' button includes:
DataRow dr;
dr = dsDetail.Tables["SalesOrderDetails"].NewRow();
dr["Amount"] = Convert.ToDecimal(txtSellingPrice.Text) * Convert.ToDecimal(txtQuantity.Text);
The Amount field in my SalesOrderDetails table has the datatype decimal(18,2)
You can force a culture and use decimal.Parse
decimal d = decimal.Parse("14,500.00", CultureInfo.InvariantCulture); // 14500
Is Convert.ToDecimal() appropriate in this case?
Yes, you could also continue to use Convert.ToDecimal if you want:
d = Convert.ToDecimal("14,500.00", CultureInfo.InvariantCulture);
I would give decimal.TryParse a go
decimal d;
if(decimal.TryParse(textbox.Text, out d))
{
//do something
}
I suspect you're using a culture that defines . as the thousands separator and , as the decimal separator. If you want to force , and . as the thousands and decimal separators, respectively then use:
decimal value = Convert.ToDecimal(textbox.text,CultureInfo.InvariantCulture);
Is Convert.ToDecimal() appropriate in this case?
It's fine - the main difference is it supports more types than decimal.Parse, which only supports strings.
I agree with #matt_lethargic, but offer a more complete solution. Tested with XUnit :)
[Theory]
[InlineData("en-US","44.00")]
[InlineData("es-PE", "44,00")]
[InlineData("es-PE", "44.00")]
[InlineData("es-PE", "0.01E-15")]
[InlineData("es-PE", "0,01E-15")]
public void ParsesDeciaml(string culture, string dec)
{
CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo(culture);
decimal d;
if (!decimal.TryParse(dec, out d)
&& !decimal.TryParse(
dec,
System.Globalization.NumberStyles.Any,
System.Globalization.CultureInfo.CurrentCulture,
out d
)
&& !decimal.TryParse(
dec,
System.Globalization.NumberStyles.Any,
System.Globalization.CultureInfo.InvariantCulture,
out d
)
) Assert.False(true, dec);
}
That way you can capture values with exponential formats.

Format decimal with positive negative and zero value to 2 decimal places format

I have a parameter price which is of type decimal it can have a positive, negative and zero value. The value will never have a decimal but needs to display a decimal.
While I parse the decimal it does handle 0 and > 0 values but does not handle negative values. How can I handle all 3 in one parse operation?
decimal.Parse(a.price.ToString("##.00"), NumberStyles.AllowDecimalPoint)
I need to convert the data to show in European culture so value of -3.00 should show up as -3,00.
Here is what I am trying and it gives me an exception
var culture = CultureInfo.GetCultureInfo("nl-NL");
Price = a.GroupId == g ? decimal.Parse(a.BidPrice.ToString("##.000", culture), NumberStyles.Number) : decimal.Parse(decimal.Zero.ToString("##.000", culture), NumberStyles.Number)
A first chance exception of type 'System.FormatException' occurred in mscorlib.dll
Additional information: Input string was not in a correct format.
Adding some test data,
3 should show up as 3,00
-3 should show up as -3,00
0 should show up as 0,00
Edit
The default culture is en-GB
Try NumberStyles.Number, that'll work:
decimal price = -3;
decimal result = decimal.Parse(price.ToString("##.00"), NumberStyles.Number);
//Result: -3,00 (comma because I live in Europe :D)
Hope this helps!
Edit:
To ensure a comma use the German CultureInfo as they use a comma for a decimal and the period as the thousand separator:
decimal price = -3;
decimal result = decimal.Parse(price.ToString("##.00", CultureInfo.GetCultureInfo("de-DE")), NumberStyles.Number);

How do I convert a string to a decimal, and format it for pretty output?

I want to convert "372551.40" to decimal. But I need to see it after converting this format 372.551,40.
To convert it to decimal, you can use:
decimal decimalValue = 0.0;
decimalValue = decimal.Parse("372551.40");
or
decimal.TryParse("372551.40", out decimalValue);
To display it in a specific format you can do:
CultureInfo tr = new CultureInfo("tr-TR");
string formattedValue = decimalValue.ToString("c", tr);
//result will be 372.551,40 YTL
formattedValue = decimalValue.ToString("0,0.00", tr);
//result will be 372.551,40
string value;
Decimal number;
value = "16,523,421";
if (!Decimal.TryParse(value,out number))
{
// set it to something if the "Value" is not a number
number = -1;
}
Do the following:
string s = "372551.40";
CultureInfo cultureInfo = CultureInfo.InvariantCulure; //Use relevant culture in which your number is formatted. In this case InvariantCulture would do.
decimal d;
bool succesful = Decimal.TryParse(s, NumberStyles.Number, cultureInfo, out d); //it will try to parse the string according to the specified culture.;
If you have a succesful parse, then d will store the numeric value represented by s as a decimal value which you can output into any formatted string and culture the ToString() or Format.String().
Note that if the culture in which the number represented by s is the current system culture, then you can use the TryParse(string s, out decimal d) overload where it is not necessary to specify NumberStyles and IFormatProvider.
Something like this?
string s = "372551.40";
decimal d;
if (decimal.TryParse(s, out d))
{
var culture = new CultureInfo("de-DE");
var result = d.ToString("0,0.00", culture);
// result is "372.551,40"
}
You can also use the current culture instead of hard-coding one like I did.
Hope this helps,
John
Use decimal.Parse() to make it a decimal. Then you have many formatting options.
The display as you mentioned is dependent on the culture setting.
Make your new CultureInfo and in the NumberFormat, you will have to modify some settings like Decimal Separator as , and Thousands Separator as . and provide this to the ToString method of the variable holding the decimal value.
This should display the value as 372.551,40
You can use .Replace
string string 1 = "372,551.40";
string1.Replace(",","");
decimalVal = System.Convert.ToDecimal(StringVal);
//shows 372551.40
You can always throw that into a for loop if you are playign with a ton of numbers.
You can find more in depth info and some examples on MSDN
The overload of decimal.Parse that takes an IFormatProvider will allow you to parse strings containing numbers with periods as decimal point symbols (in case the standard is a comma in your culture).
You can use ToString on the resulting decimal to format it with a comma by passing in an appropriate IFormatProvider. Both CulturInfo and NumberFormatInfo implement IFormatProvider.
You can get an instance of CultureInfo with the following code (this one is for English in Australia).
new CultureInfo("en-AU")
Also note that decimal.TryParse is a good alternative to the decimal.Parse method if you expect incorrectly formatted strings as it will allow you to handle them without an exception being raised.
The following code should give you the desired result (you wrote in one of the comments that the target system is SAP and that the culture is probably German (de-DE)).
var yourString = "372551.40";
var yourDecimal = decimal.Parse(yourString, CultureInfo.InvariantCulture);
var yourFormattedDecimal = yourDecimal.ToString(new CultureInfo("de-DE"));
From MSDN:
string value;
decimal number;
// Parse an integer with thousands separators.
value = "16,523,421";
number = Decimal.Parse(value);
Console.WriteLine("'{0}' converted to {1}.", value, number);
// Displays:
// 16,523,421' converted to 16523421.
Cheers
You can create custom NumberFormatInfo:
string s = "372551.40";
var dec = decimal.Parse(s, CultureInfo.InvariantCulture);
var nfi = new CultureInfo("en-US", false).NumberFormat;
nfi.NumberGroupSeparator = ".";
nfi.NumberDecimalSeparator = ",";
var res = dec.ToString("n", nfi);
var resDecimal = decimal.Parse(res, nfi);
Output is exactly what you need: 372.551,40

Convert string to Double C#

I have a field in DB which is float. My application is WindowsForm. I need to convert the value in textbox of the format 43.27 to double.
When I do this COnvert.ToDouble(txtbox.Text) I get exception saying input string is wrong format.
How to rectify this issue
Try specifying a culture when parsing:
// CultureInfo.InvariantCulture would use "." as decimal separator
// which might not be the case of the current culture
// you are using in your application. So this will parse
// values using "." as separator.
double d = double.Parse(txtbox.Text, CultureInfo.InvariantCulture);
And to handle the error case for gracefully instead of throwing exceptions around you could use the TryParse method:
double d;
if (double.TryParse(txtbox.Text, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out d))
{
// TODO: use the parsed value
}
else
{
// TODO: tell the user to enter a correct number
}
When you want to convert a string to number, you need to be sure which format does the string use. E.g. in English, there is a decimal point (“43.27”), while in Czech, there is a decimal comma (“43,27”).
By default, the current locale is used; if you know the number uses the English conversion, you need to specify the culture explicitly, e.g.
Convert.ToDouble(txtBox.Text, CultureInfo.InvariantCulture);

Categories

Resources