简体   繁体   中英

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:

  • 25.88 -> 25.88
  • 25.50 -> 25.50
  • 25.00 -> 25.00

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

  • 25.88 -> 25.88
  • 25.50 -> 25.5
  • 25.00 -> 25

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 ?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM