我有一个具有十进制数据类型的属性让我们说“兴趣”然后我有另一个字符串类型的属性让我们说“InterestString”。
属性
public decimal Interest { get; set; }
public string InterestString { get; set; }
我想将Interest的值分配给InterestString,所以我做了以下操作。例如,假设Interest的值为4(不带小数位):
InterestString = Interest.ToString();
如果转换完成后我的InterestString
变为“4.000”但我的兴趣值只有4而没有.0000。
我想在转换后保留格式。我怎样才能摆脱那些无关紧要的小数位?
如果我这样做
InterestString = Interest.ToString("N0");
它会给我InterestString =“4”; But what if I have Interest 4.5? This will give me
InterestString =“5”`(舍入到十)。
如果我做Interest.ToString("N2")
,那将会给我2个无关紧要的小数位。我想要的行为是删除无效的小数位。
请帮忙。
答案 0 :(得分:7)
我认为System.Decimal
没有Normalize
方法,这基本上就是你想要的。如果您知道最多的小数位数,可以使用:
string x = Interest.ToString("0.######");
与您感兴趣的#符号一样多。仅填写有效数字:
using System;
class Test
{
static void Main()
{
ShowInterest(4m); // 4
ShowInterest(4.0m); // 4
ShowInterest(4.00m); // 4
ShowInterest(4.1m); // 4.1
ShowInterest(4.10m); // 4.10
ShowInterest(4.12m); // 4.12
}
static void ShowInterest(decimal interest)
{
Console.WriteLine(interest.ToString("0.#####"));
}
}