How to get 2 digit decimal when data is 13 og ikke 13,00

  • Thread starter Thread starter Kim S
  • Start date Start date
K

Kim S

I try from a textbox writing a decimal value with 2 decimal value. If I write
13 meaning 13.00 curreny value I only get 13 even I use NumberForvartInfo

decimal? => use of null value with fault conveting

private static Decimal? StrToDecimal(string str)
{
int p1 = str.IndexOfAny("0123456789+-.,".ToCharArray(), 0);
if (p1 == -1) return null;

int p2 = str.IndexOf(" ", p1);
if (p2 != -1)
{
str = str.Substring(p1, p2 - p1 + 1);
}

NumberFormatInfo provider = new NumberFormatInfo();
provider.NumberDecimalSeparator = ",";
provider.NumberDecimalDigits = 2;

decimal? dbl;

try
{
dbl = System.Convert.ToDecimal(str, provider);
}
catch
{
dbl = null;
}
return dbl;

}

Then I write the value to Cell I use .ToString but still only read xx in
datagridview and not hwat I want xxx,xx


Kim S.
 
I try from a textbox writing a decimal value with 2 decimal value. If I write
13 meaning 13.00 curreny value I only get 13 even I use NumberForvartInfo

decimal? => use of null value with fault conveting

      private static Decimal? StrToDecimal(string str)
        {
            int p1 = str.IndexOfAny("0123456789+-.,".ToCharArray(), 0);
            if (p1 == -1) return null;

            int p2 = str.IndexOf(" ", p1);
            if (p2 != -1)
            {
                str = str.Substring(p1, p2 - p1 + 1);
            }

            NumberFormatInfo provider = new NumberFormatInfo();
            provider.NumberDecimalSeparator = ",";
            provider.NumberDecimalDigits = 2;

            decimal? dbl;

            try
            {
                dbl = System.Convert.ToDecimal(str, provider);
            }
            catch
            {
                dbl = null;
            }
            return dbl;

        }

Decimal (and any other numeric type) does not preserve extra leading
and trailing zeros. This is by design - after all a number "13" is
precisely equal to number "13.00". If you want the user to see the
latter, you'll have to apply the appropriate formatting when
converting decimal to string before displaying - see below.
Then I write the value to Cell I use .ToString but still only read xx in
datagridview and not hwat I want xxx,xx

Use ToString("F2"). Or better yet, if you want to display string
according to the locale selected by the user (in Control Panel ->
Regional Settings), use ToString("C").
 
Back
Top