Ben
Ben

Reputation: 2715

Convert string to decimal to always have 2 decimal places

I'm trying to convert a string to a decimal to always have 2 decimal places. For example:

But with my code below i'm seeing the following:

My Code:

Decimal.Parse("25.50", CultureInfo.InvariantCulture);

OR

Decimal.Parse("25.00");

OR

Convert.ToDecimal("25.50");

For all I get 25.5. Is it possible to not cut off the excess zeros?

Upvotes: 3

Views: 15936

Answers (2)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

Decimal is a bit strange type, so, technically, you can do a little (and may be a dirty) trick:

// This trick will do for Decimal (but not, say, Double) 
// notice "+ 0.00M"
Decimal result = Convert.ToDecimal("25.5", CultureInfo.InvariantCulture) + 0.00M; 

// 25.50 
Console.Write(result);

But much better approach is formatting (representing) the Decimal to 2 digits after the decimal point whenever you want to output it:

Decimal d = Convert.ToDecimal("25.50", CultureInfo.InvariantCulture);

// represent Decimal with 2 digits after decimal point
Console.Write(d.ToString("F2"));

Upvotes: 6

Ray P.
Ray P.

Reputation: 1

I'm surprised you're getting that issue at all, but if you want to fix it:

yourNumber.ToString("F2") It prints out to 2 decimal points, even if there are more or less decimal pointers.

Tested with:

decimal d1 = decimal.Parse("25.50");
decimal d2 = decimal.Parse("25.23");
decimal d3 = decimal.Parse("25.000");
decimal d4 = Decimal.Parse("25.00");

Console.WriteLine(d1 + " " + d2 + " " + d3.ToString("F2") + " " + d4);
Console.ReadLine();

Output: 25.50 25.23 25.00 25.00

Upvotes: 0

Related Questions