1

i want to parse like:

3.5 -> 3.5
3.484 -> 3.48
3.82822 -> 3.82

etc. However,

decimal.Parse("3.543") 

yields 3543 and so i did:

decimal.Parse("3.543",CultureInfo.InvariantCulture) 

yields 3.543 and but

decimal.Parse(String.Format("{0:0.00}","3.543"),CultureInfo.InvariantCulture);

yields 3543

so how can i do it???

jacky brown
  • 271
  • 2
  • 7
  • 20

4 Answers4

1

You need Round method:

decimal t = 3.82822;
decimal.Round(t, 2);

Where 2 show the decimal points you need.

M_Idrees
  • 2,080
  • 2
  • 23
  • 53
1

Use Math.Round like this:

decimal a = 1.9946456M;

Math.Round(a, 2); //returns 1.99

decimal b = 1.9953454M;

Math.Round(b, 2); //returns 2.00
lem2802
  • 1,152
  • 7
  • 18
0

I guess you want to truncate the decimal places after two digits. Give this a try:

public decimal TruncateDecimal(decimal value, int precision)
{
    decimal step = (decimal)Math.Pow(10, precision);
    int tmp = (int)Math.Truncate(step * value);
    return tmp / step;
}

decimal t = 3.82822;
decimal d = TruncateDecimal(t, 2);
Community
  • 1
  • 1
NeverHopeless
  • 11,077
  • 4
  • 35
  • 56
0

You should use a culture that actually uses a comma as a decimal seperator.

CultureInfo.GetCultureInfo("fr-fr")

for example.

 Console.WriteLine(decimal.Parse("3,543", CultureInfo.InvariantCulture)); // 3543
 Console.WriteLine(decimal.Parse("3,543", CultureInfo.GetCultureInfo("fr-fr"))); //3,543

and if you want to round the result. You could use

Console.WriteLine(String.Format("{0:0.00}", decimal.Parse("3,543", CultureInfo.GetCultureInfo("fr-fr")))); //3,54
Stijn Van Antwerpen
  • 1,840
  • 17
  • 42