jacky brown
jacky brown

Reputation: 271

Convert decimal with comma and floating point

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???

Upvotes: 1

Views: 106

Answers (4)

Stijn Van Antwerpen
Stijn Van Antwerpen

Reputation: 1988

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

Upvotes: 0

NeverHopeless
NeverHopeless

Reputation: 11233

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

Upvotes: 0

lem2802
lem2802

Reputation: 1162

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

Upvotes: 1

M_Idrees
M_Idrees

Reputation: 2172

You need Round method:

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

Where 2 show the decimal points you need.

Upvotes: 1

Related Questions