简体   繁体   中英

Rounding and formatting the nullable decimal in c#

Im using the below code to round the decimal to 2 decimal places.

  decimal? RTime = RTime.HasValue ? Decimal.Round(RTime.Value, 2) : 0;

But converting numberlike 512->512.00 is not working..How do i do that?

Decimal.Round rounds the value of the decimal. For example 512.123 to 512.12 .

What you want is a string representation . You need to format the value instead of rounding . You can use ToString() for that:

decimal? RTime = RTime.HasValue ? Decimal.Round(RTime.Value, 2) : 0;
string RTimeAsString = RTime.Value.ToString("0.00");

or string.Format or string interpolation like this:

string RTimeAsString = string.Format("{0:0.00}", RTime);
string RTimeAsString = $"{RTime:0.00}"

I think you are confusing rounding and formatting.

  • What you are doing is rounding and it works.
  • What you expect is formatting, ie. the way it is displayed on screen. For this you should use the .ToString() method with a corresponding format.

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