c#实现去掉数值型字符串末尾的小数点和0
时间: 2024-03-16 21:43:50 浏览: 22
可以使用以下代码实现:
```csharp
string str = "123.4500";
str = str.TrimEnd('0').TrimEnd('.');
```
首先使用`TrimEnd('0')`去掉末尾的0,然后再使用`TrimEnd('.')`去掉可能存在的小数点。最终得到的字符串为"123.45"。
相关问题
c#判断数值型字符串的小数位数
你可以使用以下代码来判断数值型字符串的小数位数:
```csharp
string numStr = "123.456";
int decimalPlaces = 0;
if (decimal.TryParse(numStr, out decimal num))
{
decimalPlaces = BitConverter.GetBytes(decimal.GetBits(num)[3])[2];
Console.WriteLine($"Number of decimal places: {decimalPlaces}");
}
else
{
Console.WriteLine("Invalid number format.");
}
```
这里使用了 `decimal.TryParse` 方法将字符串转换为 `decimal` 类型,然后使用 `decimal.GetBits` 和 `BitConverter.GetBytes` 方法来获取小数位数。如果字符串无法转换为 `decimal` 类型,则会输出错误信息。
c#,取字符串末尾3个字符
你可以使用C#中的Substring()方法获取字符串的末尾3个字符,代码如下:
```
string str = "Hello World";
string lastThree = str.Substring(str.Length - 3);
Console.WriteLine(lastThree); // 输出 "rld"
```
在这里,我们使用了字符串的Length属性来找到字符串的末尾位置,然后使用Substring()方法获取末尾3个字符。