Converting string with many leading zeros to decimal - c#

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

Related

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

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.

C# - invariant culture

I'm trying to convert a double to a decimal with a dot instead of a comma. I feel like I have tried every single possible way (except a working one) so I'm out of ideas.
double amount = myUsd / price;
string amountAsString = amount.ToString();
decimal value = Decimal.Parse(amountAsString, CultureInfo.InvariantCulture);
This one gives a FormatException for example.
Thanks
As Hans Passant said, if you Parse in the same way as you Format you'll avoid a lot of issues -> Use string amountAsString = amount.ToString(CultureInfo.InvariantCulture);
EDIT
Since you're passing in an exponential notation you need to tell the Parser this. This worked with your example value:
decimal value = Decimal.Parse(amountAsString, System.Globalization.NumberStyles.Float, CultureInfo.InvariantCulture);
But I suggest NOT formatting it as a Double. First convert it to a Decimal. Then parse it as a Decimal:
double amount = myUsd / price;
Decimal decAmount = (Decimal)amount;
string amountAsString = decAmount.ToString(CultureInfo.InvariantCulture);
decimal value = Decimal.Parse(amountAsString, CultureInfo.InvariantCulture);
Then it'll never get formatted in exponential notation.
Also see this C# Fiddle snippet

Wrong parsing from string to double

double value = double.Parse("4655.927411110702", CultureInfo.InvariantCulture);
Why this parsing is getting me result: 4655.9274111107025?
Somehow it adds to my number 5 at the end. How should I convert this string to double and have a correct result?
You can't. Not all numbers can be represented exactly in double precision floating point, and the closest such double to 4655.927411110702 is 4655.927411110702450969256460666656494140625, and the default formatting you're using trims off the majority of the "joke" digits.
C# does have a decimal type. Can you not use that?
decimal value = decimal.Parse("4655.927411110702", 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.

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