Reputation: 271
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
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
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
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
Reputation: 2172
You need Round method:
decimal t = 3.82822;
decimal.Round(t, 2);
Where 2 show the decimal points you need.
Upvotes: 1