简体   繁体   English

在 C# 中舍入和格式化可为空的小数

[英]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?但是转换 numberlike 512->512.00 不起作用..我该怎么做?

Decimal.Round rounds the value of the decimal. Decimal.Round四舍五入十进制值。 For example 512.123 to 512.12 .例如512.123512.12

What you want is a string representation .你想要的是一个字符串表示 You need to format the value instead of rounding .您需要格式化值而不是舍入 You can use ToString() for that:您可以为此使用ToString()

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.Format或字符串插值,如下所示:

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.为此,您应该使用具有相应格式的 .ToString() 方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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