[英]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.123
到512.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.我认为您混淆了舍入和格式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.